Factory-girl创建的模型绕过了我的验证。

99

我正在使用Factory Girl在我的模型/单元测试中创建两个Group实例。我正在测试该模型以检查对.current的调用是否只返回根据过期属性为“current”的组,如下所示...

  describe ".current" do
    let!(:current_group) { FactoryGirl.create(:group, :expiry => Time.now + 1.week) }
    let!(:expired_group) { FactoryGirl.create(:group, :expiry => Time.now - 3.days) }

    specify { Group.current.should == [current_group] }
  end

我的问题是,我在模型中设置了验证规则来检查新组的到期日期是否在今天日期之后。这将引发以下验证失败。

  1) Group.current 
     Failure/Error: let!(:expired_group) { FactoryGirl.create(:group, :expiry => Time.now - 3.days) }
     ActiveRecord::RecordInvalid:
       Validation failed: Expiry is before todays date
有没有一种强制创建 Group 或绕过使用 Factory Girl 创建时的验证的方法?
12个回答

0

在编程中,为了跳过验证,可以选择向 FactoryBot trait 添加一个选项,这是一些竞争答案所建议的。另一种方法是为特定的测试用例存根模型。虽然这会增加几行代码,但更易于发现。此外,您还可以更好地控制要避免调用哪些方法。

现代 RSpec 示例:

before(:each) do
  allow_any_instance_of(MyModel).
    to receive(:my_validation_method).
    and_return(nil)
end

-1

或者你可以像这样同时使用FactoryBotTimecop

trait :expired do
  transient do
    travel_backward_to { 2.days.ago }
  end
  before(:create) do |_instance, evaluator|
    Timecop.travel(evaluator.travel_backward_to)
  end
  after(:create) do
    Timecop.return
  end
end

let!(:expired_group) { FactoryGirl.create(:group, :expired, travel_backward_to: 5.days.ago, expiry: Time.now - 3.days) }

编辑:创建后请勿更新此事件,否则验证将失败。


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