我有以下规格:
describe Country do
let (:country) { Country.new(:country_code => "NL", :name => "Netherlands") }
context "when country code is empty" do
let (:country) { Country.new(:name => "Netherlands") }
it "should not be valid" do
expect(country.valid?).to be_falsey
end
it "should not save" do
expect(country.save).to be_falsey
end
end
context "when country code is not empty" do
let (:country) { Country.new(:country_code => "NL") }
it "should be valid" do
expect(country.valid?).to be_truthy
end
it "should save" do
expect(country.save).to be_truthy
end
end
context "when name is empty" do
it "should not be valid" do
expect(country.valid?).to be_falsey
end
it "should not save" do
expect(country.save).to be_falsey
end
end
end
end
我想实现的是 let 方法中的"取消设置"属性。理想情况下,我想:
let (:country) { country.country_code = nil }
我想这样做是因为我想测试Country
的单个属性是否存在(和 NON 存在),同时保持其他属性的设置。
有很多方法可以做到这一点。
-
您可以在每个上下文中使用
#before
:before do country.code = nil #change this in another context to a non-empty code end
-
或者,您可以将顶级 let 更改为引用country_code
let
,如下所示:let (:country) { Country.new(:country_code => country_code, :name => "Netherlands") }
#immediately after context "when country code is empty" let(:country_code) { nil }
.....
#immediately after: context "when country code is not empty" do let (:country_code) { "NL" }
如果您的
context "when name is empty
需要country_code
,则将顶级代码定义为默认值。
因此,您的代码可能如下所示:
describe Country do
let (:country) { Country.new(:country_code => country_code, :name => "Netherlands") }
let(:country_code) { "NL" } #default
context "when country code is empty" do
let (:country_code) { nil }
it "should not be valid" do
expect(country.valid?).to be_falsey
end
it "should not save" do
expect(country.save).to be_falsey
end
end
context "when country code is not empty" do
let (:country_code) { "NL" }
it "should be valid" do
expect(country.valid?).to be_truthy
end
it "should save" do
expect(country.save).to be_truthy
end
end
context "when name is empty" do
it "should not be valid" do
expect(country.valid?).to be_falsey
end
it "should not save" do
expect(country.save).to be_falsey
end
end
end
end
对于应该在任何it
之前执行的特定操作,您必须使用 before
钩子块,并将:all
键传递给方法。它允许为上下文块准备一次测试:
describe "when country code is not empty" do
before(:all) { country.country_code = nil }
# ...
end
注意我用describe
关键字来对付context
。但:
根据 rspec 源代码,"上下文"只是"描述"的别名方法......
"描述"的目的是针对一个功能包装一组测试,而"上下文"是在同一状态下针对一个功能包装一组测试。
有关describe
与context
的详细信息,请参阅文章:在 RSpec 中描述与上下文。
您也可以使用before
上下文块:
before(:context) { country.country_code = nil }
context "when country code is not empty" do
# ...
end