gpt4 book ai didi

ruby-on-rails - Shoulda Rspec匹配器:on => :create

转载 作者:行者123 更新时间:2023-12-04 03:41:15 24 4
gpt4 key购买 nike

我正在使用一些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)

验证未触发,因为它仅在更新上运行,如何在更新与创建之间使用这些应匹配项?

最佳答案

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

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

幸运的是,您可以通过显式定义“主题”来解决此问题:
  describe "validation of username" do
subject { User.new }
it { should validate_uniqueness_of(:username) }
end

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

关于ruby-on-rails - Shoulda Rspec匹配器:on => :create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3134066/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com