Friday, February 9, 2007

Test validations on model with base

Testing is a fairly simple process for ruby on rails development as it's "baked right in" as Mike Clark would say. But how do we test our validate/validate_on_create/etc methods when our helpers don't quite give us the flexibility we want?

We have our built in validation helpers in the model and we can execute a simple test like below.

Customer model:
validates_presence_of :address

Related test on validation helper:
def test_invalid_with_empty_attributes
customer = Customer.new

assert !customer.valid?
assert customer.errors.invalid?(:address)
end

Now suppose you have the method validate in the ruby on rails model and wish to run a test on it. Or more specifically you want to run a test on the asserted error, "assert_equal".

In our model:
protected
def validate
errors.add_to_base 'You must have at least a business name or first name.' if firstname.blank? and business.blank?
end

In our test:
def test_presence_with_validate
customer = Customer.new(
:business => nil,
:firstname => nil,
:address => "123 House Street"
)

assert !customer.valid?
assert_equal "You must have at least a business name or first name.", customer.errors.on(:base)
end

The trick is the specify :base as the "on" method parameter.

And so we test:
# ruby test/unit/customer_test.rb -n test_presence_with_validate
Loaded suite test/unit/customer_test
Started
.
Finished in 0.057076 seconds.

1 tests, 2 assertions, 0 failures, 0 errors

No comments: