views:

134

answers:

2

I'm looking for clean and short code to test validations in Rails Unittests.

Currently I do something like this

test "create thing without name" do
    assert_raise ActiveRecord::RecordInvalid do
        Thing.create! :param1 => "Something", :param2 => 123
    end
end

I guess there is a better way that also shows the validation message?

Solution:

My current solution without an additional frameworks is:

test "create thing without name" do
    thing = Thing.new :param1 => "Something", :param2 => 123
    assert thing.invalid?
    assert thing.errors.on(:name).any?
end
+1  A: 

You don't mention what testing framework that you're using. Many have macros that make testing activerecord a snap.

Here's the "long way" to do it without using any test helpers:

thing = Thing.new :param1 => "Something", :param2 => 123
assert !thing.valid?
assert_match /blank/, thing.errors.on(:name)
Jason stewart
I use only plain Rails at the moment.
Thomas
A: 

You could give the rspec-on-rails-matchers a try. Provides you with syntax like:

@thing.should validates_presence_of(:name)
Ryan Bigg
The page says: Don't use me. I'm out of date and I break shoulda. Shoulda works with rspec now. Use that.
Thomas