0

使用 Rails 4/Mongoid,我有一个模型调用MyClass,其验证定义为:

class MyClass
  include Mongoid::Document

  ...some attributes...

  before_validation :prevalidate

  def prevalidate
    self.required_prop = false if self.required_prop_two
  end
  validate do |instance|
    puts 'VALIDATING'
    ...some more validation...
  end
end

然后我有两个 Rspec 测试,其中只有一个打印“验证”:

# This test fails, and does not print 'VALIDATING'
it 'is an invalid instance' do
  instance = Fabricate.build(:my_class)
  instance.required_prop = nil
  instance.required_prop_two = nil
  instance.should have(1).errors_on(:required_props)
end
# This test passes, and prints 'VALIDATING'
it 'is a valid instance' do
  instance = Fabricate.build(:my_class)
  instance.other_required_prop = nil
  instance.should have(1).errors_on(:other_required_prop)
end

我假设validate在检查这些错误时应该始终运行。但是,它只测试#2 中运行,从不在测试#1 中运行,我完全不知道如何跳过它。它似乎与设置第二个属性有关,因为当第二个被注释掉时, Test #1 runs validate

我知道我的例子很少,但有没有人建议这样的事情怎么会发生?

4

1 回答 1

0

对不起,伙计们,原来我对我对before_validation子句的使用感到自责:因为我最后评估的行prevalidate返回错误,它中止了验证。

def prevalidate
  self.required_prop = false if self.some_other_prop
  return true # Otherwise, it'll stop validation
end

有时,Ruby 返回最后一次评估的方式让我在这样的事情上感到很痛苦。

于 2013-09-17T03:31:25.787 回答