应该是rspec匹配器:on =>:create
我正在使用一些Shoulda rspec匹配器来测试我的模型,其中一个是:
describe Issue do it { should_not allow_value("test").for(:priority) } end
我的问题是我的模型中的validation如下所示:
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)
validation没有被触发,因为它只在更新上运行,我如何在更新和创建时使用这些应该匹配?
我认为应该更好地处理这个问题。 我碰到了这个,因为我只想在创建新用户时为我的用户模型运行我的唯一性validation检查。 这是浪费数据库查询在更新时执行它,因为我不允许更改用户名:
validates :username, :uniqueness => { :case_sensitive => false, :on => :create },
幸运的是,您可以通过明确定义“主题”来解决这个问题:
describe "validation of username" do subject { User.new } it { should validate_uniqueness_of(:username) } end
这样它只测试新实例。 对于您的情况,您可以将主题更改为已存储在数据库中的内容,并设置所有必需的字段。