首页 > 解决方案 > rspec 中是否有“非”等价物,例如“and_return”的逻辑非

问题描述

在 rspec 文档中找不到该方法,但有替代方法吗?

allow_any_instance_of(<some connection>).to receive(<post method>).and_return(200)

上面的代码块返回 200

标签: ruby-on-railsrspecrspec-rails

解决方案


你从根本上误解了做什么allow_any_instance_ofto_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被认为是代码异味并且应该避免的原因之一。


推荐阅读