【问题标题】:Rspec: Test initialize method calls another method and returns a valueRspec:测试初始化​​方法调用另一个方法并返回一个值
【发布时间】:2014-06-30 13:25:37
【问题描述】:

我想测试一下;

1) 类在其初始化方法中调用特定方法

2) 该方法返回一个特定的值。

我的代码:

it 'should call message method with a message' do
  expect_any_instance_of(MyExample).to receive(:message).with("A Message")
  MyExample.new("A Message")
end

it 'should call message method with a message and return message_var in reverse' do
  expect_any_instance_of(MyExample).to receive(:message).with("A Message").and_return("this should fail")
  MyExample.new("A Message")
end



class MyExample
  def initialize(m)
    message(m)
  end

  def message(m)
    return m.reverse
   end
 end

问题是第二个测试总是通过,无论传递给 .and_return()

任何帮助将不胜感激,谢谢! 完整代码清单:http://pastebin.com/pkNuZfC4

【问题讨论】:

    标签: ruby rspec initialization return


    【解决方案1】:

    and_return 不是期望的一部分,它是存根的一部分——它没有实际调用期望的方法,而是简单地返回传递给and_return 的参数。

    要检查消息的返回值,你需要调用它并期望它的值:

    it 'returns message_var in reverse' do
      example = MyExample.new("A Message")
    
      expect(example.message("A message")).to be == "this should fail"
    end
    

    请注意,此测试不应重复前一个案例的测试(即消息被调用)。每个测试应该只测试一件事。

    【讨论】:

    • 谢谢。所以我可以检查是否在初始化方法中调用了一个方法,但找不到返回的内容。没有明确称它是..?
    • unit test 而言 - 它不应该 matter 在您测试它是否被调用时实际返回的内容,就像if 它在您测试 what 它返回时在任何地方被调用并不重要。
    猜你喜欢
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-19
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2016-11-16
    相关资源
    最近更新 更多