Rspec before(:each) 有效但 before(:all) 无效
Rspec before(:each) works but before(:all) does not
我的产品类别规范:-
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
在所有例子之前只有运行s一次,所以@product_category
被创建了一次。如果你在每次测试后有类似 DatabaseCleaner t运行cation 运行ning 的东西,记录在第二次测试中不再在数据库中,从而通过验证。
另一方面,before :each
将在每个示例之前 运行,因此即使在此期间清理了数据库,记录也会在第二个示例中。
我的产品类别规范:-
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
在所有例子之前只有运行s一次,所以@product_category
被创建了一次。如果你在每次测试后有类似 DatabaseCleaner t运行cation 运行ning 的东西,记录在第二次测试中不再在数据库中,从而通过验证。
before :each
将在每个示例之前 运行,因此即使在此期间清理了数据库,记录也会在第二个示例中。