9

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

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

我的问题是我在模型中的验证如下所示:

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

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

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)

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

4

1 回答 1

12

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

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

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

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

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

于 2011-03-20T22:59:00.030 回答