"Netherla-6ren">
gpt4 book ai didi

ruby-on-rails - rspec let,如何取消设置属性

转载 作者:行者123 更新时间:2023-12-02 15:30:19 25 4
gpt4 key购买 nike

我有以下规范:

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 属性是否存在(和不存在),同时保持其他属性设置。

最佳答案

有很多方法可以做到这一点。

  1. 您可以在每个上下文中使用#before:

    做之前
    country.code = nil #在另一个上下文中将其更改为非空代码
    结束

  2. 或者,您可以更改顶级 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"做
    让 (:country_code) { "NL"}

    如果您的上下文“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

关于ruby-on-rails - rspec let,如何取消设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27421090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com