Shoulda/RSpec 匹配器 - 条件验证 [英] Shoulda/RSpec matchers - conditional validation

查看:43
本文介绍了Shoulda/RSpec 匹配器 - 条件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我使用 Shoulda 匹配器进行了以下验证,效果很好:

In my code I had the following validation with Shoulda matchers, which works fine:

it { should validate_presence_of(:name) }

在我的模型中,我已将条件添加到我的验证中:

In my model, I've added the condition to my validation:

validates_presence_of :name, :if => eligible?

是否可以在验证中反映出来?

Is it possible to reflect it in the validations?

我已经尝试查看 documentation 以了解 shoulda 匹配器,但一直未能找到解决方案.

I've tried looking at documentation for shoulda matchers, but haven't been able to locate the solution.

非常感谢!

推荐答案

shouta_matchers 似乎没有这样做,但是自己编写它很容易::

It doesn't appear that shoulda_matchers does this, but it's easy enough to write it yourself::

  context "if eligible" do
    before { allow(subject).to receive(:eligible?).and_return(true) }
    it { should validate_presence_of(:name) }
  end

  context "if ineligible" do
    before { allow(subject).to receive(:eligible?).and_return(false) }
    it { should_not validate_presence_of(:name) }
  end

这篇关于Shoulda/RSpec 匹配器 - 条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆