应该匹配和条件验证错误

时间:2018-02-06 15:25:59

标签: ruby rspec shoulda

在这里,我使用属性:new_record来设置验证条件。

attr_accessor :new_record
validates :email, presence: true, email: true, unless: :new_record?

  def new_record?
    @new_record || true
  end

如果new_record? == true,将跳过电子邮件验证并且新用户有效。 我写了这个测试: it { expect(subject).to validate_presence_of(:email) } 它会返回错误:

Failure/Error: it { expect(subject).to validate_presence_of(:email) }

       User did not properly validate that :email cannot be empty/falsy.
         After setting :email to ‹nil›, the matcher expected the User to be
         invalid, but it was valid instead.

请注意,如果验证中未添加任何条件,则此测试将完美运行。此外,该代码在生产中也很有效。 我也试过了

    before(:each) do
      subject.new_record = true
    end

`before { allow(subject).to receive(:new_record?).and_return(true) }`

任何人都可以帮忙吗?

0 个答案:

没有答案