Factory_Girl linting 和 Rspec 期望 be_valid 之间的区别

Difference between Factory_Girl linting and Rspec's expect to be_valid

测试工厂[Factory_Girl Lint]1RSpec的:

...
it 'has a valid factory' do 
  expect(build(:foo)).to be_valid
end
...

我假设 Factory_Girl Lint 检查架构/数据库级别验证 null: falseRspec 期望 be_valid 检查模型级验证,例如 validates_presence_of?

Rspec 的 be_valid 期望基本上只是在模型上调用 valid?,因此只测试 ActiveRecord 验证。但是,我相信 FactoryGirl 的 lint 方法不仅会创建模型,还会保存模型,因此会测试 ActiveRecord 验证和任何数据库级验证(ActiveRecord 验证尚未涵盖)。请注意,如果由于 ActiveRecord 验证违规而导致模型实例保存失败,那么在您修复问题并再次测试之前,不会针对数据库测试该模型。

在实际层面上,我发现 Rspec 的 be_valid 期望在测试特定的有效性违规时最有用。例如:

some_record = SomeRecord.new(...minimum set of valid properties...)
some_record.property = 'invalid value'
some_record.should_not be_valid
some_record.error.full_messages.should include('expected error for the given property')

而 FactoryGirl 的 lint 方法对于测试您是否已正确构建工厂最为有用。