应该 rspec 匹配器 :on => :创造

发布于 2024-09-08 01:59:07 字数 611 浏览 0 评论 0原文

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

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

I am using some of the Shoulda rspec matchers to the test my model, one of them being:

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

My problem with this is that my validation in my model looks like this:

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

So when running this test I get:

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)

The validation isn't being triggered because it only runs on an update, how can I use these shoulda matchers on an update vs. a create?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷荒 2024-09-15 01:59:07

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

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

幸运的是,您可以通过显式定义“主题”来解决此问题:

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文