ruby-on-rails - 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) 失败的确切原因
解决方案
before :all
仅在所有示例之前运行一次,因此@product_category
创建一次。如果您在每次测试后运行类似 DatabaseCleaner 截断,则在第二次测试中记录不再存在于数据库中,从而通过验证。
before :each
另一方面,将在每个示例之前运行,因此即使在此期间清理了数据库,记录也会在第二个示例中存在。
推荐阅读
- python - 如果即使我被告知要进行虚拟化,我也选择不进行虚拟化,会出现问题吗?
- mysql - 跨列添加并显示总计
- r - 在 R 包中包含静态非数据对象?
- ios - Swift:处理 UIImage 数据以用于 Firebase 自定义 TFLite 模型
- php - 在 Woocommerce 结帐注册中通过计费名字替换用户名
- java - HandleBars 不呈现对象变量
- mongodb - mongodb collection.find 找不到文档
- python - 每组的熊猫计算两个类别的比率,并使用 .pipe() 作为新列附加到数据框
- html - 如何在按钮之间放置空间?
- html - 你如何处理条件 html 格式?