首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >RSpec3与消息期望

RSpec3与消息期望
EN

Stack Overflow用户
提问于 2014-07-31 12:41:49
回答 1查看 58关注 0票数 0

我使用的是rspec 3.0.3和ruby 2.1.2,只是不知道出了什么问题。抱歉,代码实现不好(我指的是类变量),但这是显示错误所在的更简单的方法。

我有两个班。首先,调用Test的new_method应该调用应该更改@@c_var类变量的AnotherTest.call_method。

代码语言:javascript
运行
复制
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

我正在为它写说明书:

代码语言:javascript
运行
复制
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

这个规格还可以用。但后来我试着用“期待接到电话”,出了点问题

代码语言:javascript
运行
复制
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正在进行类似于迁移的检查,并在迁移之后进行回滚。

这是一个很奇怪的例子,我知道,但是我注意到了这个错误,只有当一个类的一个实例的方法从另一个实例调用方法时,这个方法才试图改变一些东西。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-31 12:48:53

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

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

代码语言:javascript
运行
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25059137

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档