i am trying out minitest, but need some advice on a clean way to test
validations.
I setup my testing to use minitest by following the following railscast
plus i added miniskirt for Factories.
everything works well, but there has to be a cleaner way of testing
failed
validations. would i be better off using something besides “must_raise”?
if
not, is there a way to make a helper function or something to clean this
up
so it is more readable?
require “minitest_helper”
describe User do
it “rejects a bad password in validation” do
user = Factory.build(:user, :password_confirmation => ‘Not my
password’)
failed_val = lambda { user.save! }
failed_val.must_raise ActiveRecord::RecordInvalid
error = failed_val.call rescue $!
error.message.must_include “Password doesn’t match confirmation”
end
end
I usually test my validations like this:
require “minitest_helper”
describe User do
it “rejects a bad password in validation” do
user = Factory.build(:user, :password_confirmation => ‘Not my
password’)
user.invalid?(:password_confirmation).must_equal true
user.errors[:password_confirmation].must_equal “Password doesn’t
match
confirmation”
end
end
Carlos,
I love the way you are testing this. I have a question tho. When I tried
implementing something similar in my tests, it doesn’t seem to be
running the validations I set in the def validate function of my model.
Can you think of any reason why this might be happening or how I should
alternatively test to make sure it includes the validations in validate?
Also, do you test associations with minitest? An example of that would
be incredibly helpful as well.
Thanks for any help!
I’m glad you found my snippet helpful!
Testing associations is trickier, and I must admit that I don’t test
associations as thoroughly as I probably should. I usually just test
that
the record responds to the association (e.g.: record.must_respond_to
:association).
I took a look at the “shoulda-matchers” gem’s source
codehttps://github.com/thoughtbot/shoulda-matchers/blob/master/lib/shoulda/matchers/active_record/association_matcher.rb.
Those association matchers test for a whole bunch of stuff (foreign
keys,
join tables, correct class names, etc.), some of which are probably
re-testing ActiveRecord functionality which we should be able to assume
works correctly. A good test for associations should fall somewhere in
between these two extremes.
I’d love to hear if anyone else has suggestions.
Oh fun, just found out def validate doesn’t quite work like that anymore
in rails3, so never mind on the first question, I need to change my def
validate method.
An example of an association test would still be crazy helpful tho.
Here’s what I used to do with spec and shoulda:
it { should have_many(:products).through(:buying_guides_products) }
Any ideas?