我正在尝试制作rspec测试用例。但是,Rspec因为Name已经失败了。
似乎每次“产品”调用时都会“评估”。
我该如何解决?
控制台
./spec/models/spree/product_decorator_spec.rb:31:in `block (4 levels) in <top (required)>'
ActiveRecord::RecordInvalid: Validation failed: Name has already been taken
./spec/models/spree/product_decorator_spec.rb:6:in `block (3 levels) in <top (required)>'
./spec/models/spree/product_decorator_spec.rb:20:in `block (4 levels) in <top (required)>'
./spec/models/spree/product_decorator_spec.rb:23:in `block (4 levels) in <top (required)>'
ActiveRecord::RecordInvalid: Validation failed: Name has already been taken
./spec/models/spree/product_decorator_spec.rb:6:in `block (3 levels) in <top (required)>'
./spec/models/spree/product_decorator_spec.rb:12:in `block (4 levels) in <top (required)>'
./spec/models/spree/product_decorator_spec.rb:15:in `block (4 levels) in <top (required)>'
product_decorator_spec.rb
require 'spec_helper'
describe Spree::Product do
context '#create' do
let(:us) { create(:zone, name: "US") }
let(:china) { create(:zone, name: "China") }
let(:japan) { create(:zone, name: "Japan") }
context "when a product has no ng zone" do
let(:product) { create(:product, zones: [us, china, japan]) }
it "should get ng_zones correctly" do
product.ng_zones.should match_array []
end
end
context "when a product has one ng zone" do
let(:product) { create(:product, zones: [us, china]) }
it "should get ng_zones correctly" do
product.ng_zones.should match_array ["Japan"]
end
end
context "when a product has two ng zone" do
let(:product) { create(:product, zones: [us]) }
it "should get ng_zones correctly" do
product.ng_zones.should match_array ["China", "Japan"]
end
end
end
end
答案 0 :(得分:0)
使用每个let
块评估it
的正文。我假设你的Zone
类有唯一性约束。
你有两种可能性
before(:all)
块中构建变量并将其分配给@us
after(:each)
答案 1 :(得分:0)
您正在测试Product#create
,因此,您不需要为此特定测试真正创建zones
。
相反,您可以使用build_stubbed
方法。
let(:us) { build_stubbed(:zone, name: "US") }
let(:china) { build_stubbed(:zone, name: "China") }
let(:japan) { build_stubbed(:zone, name: "Japan") }
这样,它的创建过程不依赖于数据库以及Zone
模型的验证,并且你有一个很棒的性能提升,因为你没有为每个数据库命中数据库单一测试。
您可以阅读build_stubbed
here。
如果它以某种方式帮助你,请告诉我。 ;)