ruby-on-rails - rspec 中是否有“非”等价物,例如“and_return”的逻辑非
问题描述
在 rspec 文档中找不到该方法,但有替代方法吗?
allow_any_instance_of(<some connection>).to receive(<post method>).and_return(200)
上面的代码块不返回 200
解决方案
你从根本上误解了做什么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
被认为是代码异味并且应该避免的原因之一。
推荐阅读
- css - 用 css 调整 c3 轴标签
- mysql - 在 mySQL 和 Python 中选择具有最多特定值条目的列
- html - 联系表格不正确 - HTML/CSS
- visual-studio-code - 发生异常:SessionCloseError
- typescript - 在 Typescript 中,如何将接口的键映射到特定字符串的数组中?
- node.js - 提交更改时 Gitlab CI/CD 挂起
- c - CodeLite MinGW32 无法链接到 .dll.a 文件
- kubernetes - Spot 实例未加入 terraform 0.13.5 提供的 aws eks 1.18
- google-cloud-firestore - Firestore 中的文档 ID 和文档名称有什么区别?
- java - 如何使 Android 应用程序加载到徽标中然后返回到主要活动?