【问题标题】:Rspec before(:each) works but before(:all) does notRspec before(:each) 有效,但 before(:all) 无效
【发布时间】:2018-12-18 08:03:07
【问题描述】:

我的产品类别规范:-

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) 失败的确切原因

【问题讨论】:

  • 失败并出现什么错误?
  • 因预期错误而失败?还是有其他错误?我猜对了类别名称应该是唯一的吗?你使用数据库清理器还是config.use_transactional_fixtures

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-19
    相关资源
    最近更新 更多