在rspec文档中找不到该方法,但是有替代方法吗?
allow_any_instance_of(<some connection>).to receive(<post method>).and_return(200)
上面的代码块不返回200代替
答案 0 :(得分:1)
您从根本上误解了allow_any_instance_of
和to_return
的作用。
allow_any_instance_of
用于在给定类的任何实例上添加方法。它没有设定任何期望-expect_any_instance_of
可以设定。
class Foo
def bar(*args)
"baz"
end
end
RSpec.describe Foo do
describe "allow_any_instance_of" do
it "does not create an expectation" do
allow_any_instance_of(Foo).to receive(:bar).and_call_original
expect(true).to be_truthy
end
end
describe "expect_any_instance_of" do
it "sets an expectation" do
expect_any_instance_of(Foo).to receive(:bar).and_call_original
expect(Foo.new.bar).to eq 'baz'
end
# this example will fail
it "fails if expected call is not sent" do
expect_any_instance_of(Foo).to receive(:bar).and_call_original
expect(true).to be_truthy
end
end
end
.and_return
用于设置模拟/存根的返回值。正如您似乎认为的那样,它并没有为返回值设定期望。
RSpec.describe Foo do
describe "and_return" do
it "changes the return value" do
allow_any_instance_of(Foo).to receive(:bar).and_return('hello world')
expect(Foo.new.bar).to_not eq 'baz'
expect(Foo.new.bar).to eq 'hello world'
end
end
end
当您想监视某个方法而不更改其返回值时,可以使用.and_call_original
。默认情况下,任何用allow_any_instance_of/expect_any_instance
加桩的方法都将返回nil。
AFAIK无法设置.and_call_original
的返回值的期望值。这就是为什么any_instance_of
被认为是代码异味的原因之一,应该避免。