我使用的是rspec 3.0.3和ruby 2.1.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正在进行类似于迁移的检查,并在迁移之后进行回滚。
这是一个很奇怪的例子,我知道,但是我注意到了这个错误,只有当一个类的一个实例的方法从另一个实例调用方法时,这个方法才试图改变一些东西。
发布于 2014-07-31 12:48:53
通过使用expect(...).to receive(...),不会调用原始方法。相反,当调用它时,它只返回传递给and_return(...)的任何内容,而不实际执行您的方法。
你可能想要的是and_call_original。通过这种方式,您可以确保调用该方法,并且仍然允许它执行:
expect(AnotherTest).to receive(:call_method).and_call_originalhttps://stackoverflow.com/questions/25059137
复制相似问题