Shoulda rspec matchers :on => :create

╄→гoц情女王★ 提交于 2019-12-04 02:53:27

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!