应该是rspec匹配器:on =>:create

tro*_*ock 9 unit-testing rspec ruby-on-rails shoulda

我正在使用一些Shoulda rspec匹配器来测试我的模型,其中一个是:

describe Issue do
  it { should_not allow_value("test").for(:priority) }
end
Run Code Online (Sandbox Code Playgroud)

我的问题是我的模型验证如下:

validates_format_of :priority, :with => /^(Low|Normal|High|Urgent)$/, :on => :update
Run Code Online (Sandbox Code Playgroud)

因此,当运行此测试时,我得到:

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)
Run Code Online (Sandbox Code Playgroud)

验证没有被触发,因为它只在更新上运行,我如何在更新和创建时使用这些应该匹配?

mys*_*ute 12

我认为应该更好地处理这个问题.我碰到了这个,因为我只想在创建新用户时为我的用户模型运行我的唯一性验证检查.在更新时执行此操作会浪费数据库查询,因为我不允许更改用户名:

validates :username, :uniqueness => { :case_sensitive => false, :on => :create },
Run Code Online (Sandbox Code Playgroud)

幸运的是,您可以通过明确定义"主题"来解决这个问题:

  describe "validation of username" do
      subject { User.new }
      it { should validate_uniqueness_of(:username) }  
  end
Run Code Online (Sandbox Code Playgroud)

这样它只测试一个新实例.对于您的情况,您可以将主题更改为已经保存在数据库中的内容,并设置所有必需的字段.