Shoulda rspec matchers :on => :create
Asked Answered
E

1

9

I am using some of the Shoulda rspec matchers to the test my model, one of them being:

describe Issue do
  it { should_not allow_value("test").for(:priority) }
end

My problem with this is that my validation in my model looks like this:

validates_format_of :priority, :with => /^(Low|Normal|High|Urgent)$/, :on => :update

So when running this test I get:

1) 'Issue should not allow priority to be set to "test"' FAILED
   Expected errors when priority is set to "test", got errors: category is invalid (nil)title can't be blank (nil)profile_id can't be blank (nil)

The validation isn't being triggered because it only runs on an update, how can I use these shoulda matchers on an update vs. a create?

Eccrine answered 28/6, 2010 at 16:7 Comment(0)
A
12

I think shoulda should handle this better. I ran into this because I only want to run my uniqueness validation check for my User model when creating new users. It's a waste of a database query doing it on update, since I don't allow usernames to be changed:

validates :username, :uniqueness => { :case_sensitive => false, :on => :create },

Fortunately you can get around this by explicitly defining the "subject":

  describe "validation of username" do
      subject { User.new }
      it { should validate_uniqueness_of(:username) }  
  end

This way it's only testing on a new instance. For your case, you can probably just change the subject to be something saved in the database already, with all the necessary fields set.

Adnah answered 20/3, 2011 at 22:59 Comment(1)
Thanks @endium. Similarly, subject { FactoryGirl.create(:user) } can be used to test on: :update-only validations.Randolphrandom

© 2022 - 2024 — McMap. All rights reserved.