Rspec:Test initialize方法调用另一个方法并返回一个值

时间:2014-06-30 13:25:37

标签: ruby rspec initialization return

我想测试一下;

1)一个类在其initialize方法中调用一个特定的方法

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

1 个答案:

答案 0 :(得分: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

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