Shoulda/RSpec匹配器 - 条件验证

71
在我的代码中,我使用了Shoulda匹配器进行以下验证,它运行良好:
it { should validate_presence_of(:name) }

在我的模型中,我已经添加了验证条件:
validates_presence_of :name, :if => eligible?

你能否在验证中反映它?

我已经尝试查看 shoulda matchers 的 documentation, 但还没有找到解决方案。

非常感谢!

1个回答

152

应该匹配器似乎没有这样做,但自己编写代码也很容易:

  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

11
使用RSpec 3: before { allow(subject).to receive(: eligible?).and_return(true) } 的意思是在测试运行之前,将对subjecteligible?方法的调用替换为返回true - Raf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接