首页 > 解决方案 > Rspec before(:each) 有效,但 before(:all) 无效

问题描述

我的 ProductCategory 规格:-

require 'rails_helper'

RSpec.describe ProductCategory, type: :model do
    before(:each) do 
        @product_category = create(:product_category)
    end

  context "validations" do 
    it "should have valid factory" do
        expect(@product_category).to be_valid
    end

    it "should have unique name" do 
        product_category_new = build(:product_category, name: @product_category.name)
        expect(product_category_new.save).to be false
    end
  end
end

规范运行良好,但是当我使用 before(:all) 而不是 before(:each) 时,第二个示例失败 -
expected false got true我知道 before(:all) 和 before(:each) 之间的区别,但我无法找到第二个示例因 before(:all) 失败的确切原因

标签: ruby-on-railsrspecruby-on-rails-5factory-bot

解决方案


before :all仅在所有示例之前运行一次,因此@product_category创建一次。如果您在每次测试后运行类似 DatabaseCleaner 截断,则在第二次测试中记录不再存在于数据库中,从而通过验证。

before :each另一方面,将在每个示例之前运行,因此即使在此期间清理了数据库,记录也会在第二个示例中存在。


推荐阅读