【问题标题】:RSpec3 and message expectationsRSpec3 和消息期望
【发布时间】:2014-07-31 12:41:49
【问题描述】:

我正在使用 rspec 3.0.3 和 ruby​​ 2.1.2,但无法弄清楚出了什么问题。 抱歉代码实现不好(我的意思是类变量),但这是显示问题所在的更简单方法。

我有 2 节课。首先调用 Test 类的 new_method 应调用应更改 @@c_var 类变量的 AnotherTest.call_method。

require "rspec"

class Test
  def self.new_method
    AnotherTest.call_method
  end
end

class AnotherTest

  @@c_var = "hola"

  def self.call_method
     @@c_var = "holla from another test"
  end

  def self.c_var
    @@c_var
  end

end

我正在为它写规范:

describe Test do
  it "should call method from an other class" do
    Test.new_method
    expect(AnotherTest.c_var).to be_eql("holla from another test")
  end
end

而且这个规格工作正常。但是后来我尝试使用“期望接听电话”出现问题

describe Test do
  it "should call method from an other class" do
    expect(AnotherTest).to receive(:call_method).and_return("holla from another test")
    Test.new_method
    expect(AnotherTest.c_var).to be_eql("holla from another test")

  end
end

Failures:

1) Test should call method from an other class
 Failure/Error: expect(AnotherTest.c_var).to be_eql("holla from another test")
   expected `"hola".eql?("holla from another test")` to return true, got false
 # ./test.rb:26:in `block (2 levels) in <top (required)>'

似乎 RSpec 正在像迁移一样进行此检查并在其后进行回滚。

这是一个很奇怪的示例,我知道,但我注意到这个错误只有在一个类实例的方法从另一个实例调用方法并且该方法试图改变某些东西时。

【问题讨论】:

    标签: ruby-on-rails rspec rspec3


    【解决方案1】:

    通过使用expect(...).to receive(...),不会调用原始方法。相反,当它被调用时,它只会返回您传递给 and_return(...) 的任何内容,而不会实际执行您的方法。

    您可能想要的是and_call_original。这样,您可以确保调用该方法,并且仍然允许它执行:

    expect(AnotherTest).to receive(:call_method).and_call_original
    

    来源:https://www.relishapp.com/rspec/rspec-mocks/v/3-0/docs/configuring-responses/calling-the-original-implementation

    【讨论】:

    • 我以为这样的逻辑在allow(...).to receive(...).and_return(...)上。
    • 不; allow 基本上将其存根,但如果调用该方法则不会使测试失败;如果从不调用该方法,expect 将失败。在这两种情况下,除非您使用 and_call_original 告诉它,否则永远不会执行实际方法
    • 感谢您的回答。这是一个有点奇怪的逻辑,但看起来你是对的:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多