Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shoulda rspec matchers :on => :create

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?

like image 710
trobrock Avatar asked Feb 03 '23 04:02

trobrock


1 Answers

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.

like image 120
mysticflute Avatar answered Feb 07 '23 17:02

mysticflute