Rspec:: 允许每个实例接收一条消息
Rspec:: allow every instance to receive a message
我想为 class 的每个实例模拟一个方法。
如果我 allow_any_instance_of 那么如果 instance_count = 1
效果很好
但是,如果我有很多相同的实例 class,则第二个实例不会被模拟捕获。
我正试图从不同的站点获取一堆代币。但是在测试过程中,我真的不需要 "real" 个令牌。所以我打算模拟 get_token 到 return '1111'。
class Foo
def children
[Bar.new, Bar.new] #....
end
def get_tokens
children.map(&:get_token) || []
end
end
所以现在我如何不模拟 get_tokens?
这样的解决方案怎么样:
require "spec_helper"
require "ostruct"
class Bar
def get_token
("a".."f").to_a.shuffle.join # simulating randomness
end
end
class Foo
def children
[Bar.new, Bar.new, Bar.new]
end
def get_tokens
children.map(&:get_token) || []
end
end
RSpec.describe Foo do
before do
allow(Bar).to receive(:new).and_return(OpenStruct.new(get_token: "123"))
end
it "produces proper list of tokens" do
expect(Foo.new.get_tokens).to eq ["123", "123", "123"]
end
end
我们将 Bar
上的 new
方法存根到 return 某物 庸医使用 get_token
(因此它的行为类似于 Bar
),并且 return 是一个固定字符串。这是你可以转发的东西。
希望对您有所帮助!
我想为 class 的每个实例模拟一个方法。 如果我 allow_any_instance_of 那么如果 instance_count = 1
效果很好但是,如果我有很多相同的实例 class,则第二个实例不会被模拟捕获。
我正试图从不同的站点获取一堆代币。但是在测试过程中,我真的不需要 "real" 个令牌。所以我打算模拟 get_token 到 return '1111'。
class Foo
def children
[Bar.new, Bar.new] #....
end
def get_tokens
children.map(&:get_token) || []
end
end
所以现在我如何不模拟 get_tokens?
这样的解决方案怎么样:
require "spec_helper"
require "ostruct"
class Bar
def get_token
("a".."f").to_a.shuffle.join # simulating randomness
end
end
class Foo
def children
[Bar.new, Bar.new, Bar.new]
end
def get_tokens
children.map(&:get_token) || []
end
end
RSpec.describe Foo do
before do
allow(Bar).to receive(:new).and_return(OpenStruct.new(get_token: "123"))
end
it "produces proper list of tokens" do
expect(Foo.new.get_tokens).to eq ["123", "123", "123"]
end
end
我们将 Bar
上的 new
方法存根到 return 某物 庸医使用 get_token
(因此它的行为类似于 Bar
),并且 return 是一个固定字符串。这是你可以转发的东西。
希望对您有所帮助!