gpt4 book ai didi

ruby-on-rails-4 - RSpec:如何 stub 方法和方法链

转载 作者:行者123 更新时间:2023-12-02 04:21:58 25 4
gpt4 key购买 nike

我有一个单例类,许多其他类和 Controller 可以访问该类来确定行为。如何在测试中设置单例值以便测试行为。下面的示例代码中,Setting 是一个 Singleton 类,它由数据库支持并存储应用程序范围的设置,并且管理员可以更改这些设置。 Floodgate 是一个访问设置的类。

class Setting
def instance
@setting ||= new
end
end

class Floodgate
def self.whitelist
Setting.instance.flood_gate_whitelist
end
end

以下是 Floodgate 的一些测试,需要访问设置数据库值。

describe Floodgate do
let(:setting) { Class.create(Setting).instance }

describe ".whitelist" do
it "returns a list of values on the Settings floodgate whitelist" do
expect(Floodgate.whitelist).to eq 'google'
end
end

describe ".allow_traffic_source?" do
it "returns true if traffic source is on the white list" do
expect(Floodgate.allow_traffic_source?('google')).to eq true
end

it "returns false if traffic source is not on the white list" do
expect(Floodgate.allow_traffic_source?('facebook')).to eq false
end
end

上面的第一个和第二个测试失败,因为Setting.flood_gate_whitelist为nil。在 Floodgate 测试中,我如何设置它以便它持续存在,atm d/b 中没有记录。我尝试如下显式设置它,当我使用 create 时,错误响应是未定义的方法“create”。

let(:setting) { Class.new(Setting, flood_gate_whitelist: 'google').instance } 

最佳答案

对正在调用的消息链进行 stub 处理。在您的情况下,一个例子是:

before do
allow(Setting).
to receive_message_chain("instance.flood_gate_whitelist").
and_return("google")
end

现在,代码中任何位置的 Setting.instance.flood_gate_whitelist 都将返回 “google”

或者,您可以在 Setting 上 stub 实例方法,如下所示:

before do
allow_any_instance_of(Setting).
to receive(:flood_gate_whitelist).
and_return("google")
end

如果您确定正确实例化Setting,请选择后者。

顺便说一句,与配置相关的变量最好放入一个 *.yml 文件(例如 database.yml 用于哪个数据库),该文件将根据不同的情况具有不同的值当前的项目环境(在许多情况下,这将消除对 stub 方法的需要)。

关于ruby-on-rails-4 - RSpec:如何 stub 方法和方法链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29728167/

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