使用 Shoulda Matchers 测试时忽略 FactoryGirl 构建

FactoryGirl build ignored when testing with Shoulda Matchers

我最近切换到 Shoulda Matchers,但似乎无法验证我的工厂构建。我在之前的回调中实例化了我的工厂构建,但匹配器似乎甚至不承认它。例如,我故意将我的实例名称设置为 nil 但测试 returns 没有错误。我做错了什么?

require 'rails_helper'

describe Restaurant do
  context 'validations' do
    before { FactoryGirl.build(:restaurant, name: nil) }

    it do
      should validate_presence_of(:name)
    end
  end
end

对于这种情况,您不需要实例来匹配 Shoulda 匹配器;它只会根据模型定义本身测试 the usage of validate_presence_of

所以,我会这样重写你的测试:

require 'rails_helper'

describe Restaurant do
  it { should validate_presence_of(:name) }
end