我有以下规格:
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
的SINGLE属性的存在(和NON存在),同时保持其他属性设置。
答案 0 :(得分:2)
对于应在任何it
之前执行的特定操作,您必须使用before
hook块,并将:all
密钥传递给该方法。它允许为上下文块准备一次测试:
describe "when country code is not empty" do
before(:all) { country.country_code = nil }
# ...
end
注意我对describe
使用了context
个关键字。但是:
根据rspec源代码,“context”只是“describe”的别名方法......
“describe”的目的是针对一个功能包装一组测试,而“context”是针对同一状态下的一个功能包装一组测试。
describe
与context
中的更多信息,您可以阅读文章:Describe vs. Context in RSpec。
您也可以使用before
context阻止:
before(:context) { country.country_code = nil }
context "when country code is not empty" do
# ...
end
答案 1 :(得分:2)
有很多方法可以做到这一点。
您可以在每个上下文中使用#before
:
before do
country.code = nil #change this in another context to a non-empty code
end
或者,您可以更改您的顶级权限以引用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