Simple syntax for checking validation errors

I am looking for clean and short code to validate validation in Rails Unittests.

I'm currently doing something like this

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

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

Decision:

My current solution without additional frameworks:

 test "create thing without name" do thing = Thing.new :param1 => "Something", :param2 => 123 assert thing.invalid? assert thing.errors.on(:name).any? end 
+6
validation ruby-on-rails unit-testing
source share
5 answers

You do not indicate which test environment you are using. Many have macros that make the activation process active.

Here is a "long way" to do this without using any test assistants:

 thing = Thing.new :param1 => "Something", :param2 => 123 assert !thing.valid? assert_match /blank/, thing.errors.on(:name) 
+6
source share

Try accept_values_for gem. This allows you to do something like this:

 describe User do subject { User.new(@valid_attributes)} it { should accept_values_for(:email, " john@example.com ", " lambda@gusiev.com ") } it { should_not accept_values_for(:email, "invalid", nil, " a@b ", " john@.com ") } end 

This way you can easily test really complex checks.

+1
source share

I am using Rails 2.0.5, and when I want to claim that the model will not validate, I will check the errors.full_messages method and compare it with the array of expected messages.

 created = MyModel.new created.field1 = "Some value" created.field2 = 123.45 created.save assert_equal(["Name can't be blank"], created.errors.full_messages) 

To claim that the check was successful, I simply compare with an empty array. You can do something very similar to verify that the Rails controller does not have error messages after it requests to create or update.

 assert_difference('MyModel.count') do post :create, :my_model => { :name => 'Some name' } end assert_equal([], assigns(:my_model).errors.full_messages) assert_redirected_to my_model_path(assigns(:my_model)) 
+1
source share

For those who use Rails 3.2.1 and higher, do I prefer to use the method ? :

 assert record.errors.added? :name, :blank 

I am using a test assistant that looks like this:

 def assert_invalid(record, options) assert_predicate record, :invalid? options.each do |attribute, message| assert record.errors.added?(attribute, message), "Expected #{attribute} to have the following error: #{message}" end end 

Which allows me to write tests as follows:

 test "should be invalid without a name" do user = User.new(name: '') assert_invalid user, name: :blank end 
+1
source share

You can try rspec-on-rails-matchers . Provides syntax, for example:

 @thing.should validates_presence_of(:name) 
0
source share

All Articles