RSpec Book示例混淆(should_receive)

时间:2014-04-01 23:12:08

标签: ruby-on-rails ruby rspec bdd

我现在正试图遵循RSpec的书,但对我来说这似乎不太清楚。它有一个lib / codebreaker / game.rb文件:

module Codebreaker
  class Game
    def initialize(output)
      @output = output
    end
    def start
      @output.puts "Welcome to Codebreaker!" 
    end
  end
end        

我有一个spec / codebreaker / game_spec.rb文件:

require 'spec_helper'

module Codebreaker
  describe Game do
    describe "#start" do
      it "sends a welcome message" do
        output = double("output")
        game = Game.new(output)

        output.should_receive(:puts).with("Welcome to Codebreaker!")

        game.start
      end
      it "prompts for the first guess"
    end
  end
end

所以目前,“它'发送欢迎信息'”测试通过,但我不明白为什么。

game_spec文件说“输出”应该收到带有“欢迎使用Codebreaker!”的puts命令。但是,在game.rb文件中,我们清楚地看到输出是初始化方法的ARGUMENT。 @outputs,实例变量而不是参数参数,将“欢迎使用Codebreaker!”呼唤它。当明确输出没有接收时,为什么这个测试通过:puts,但@output是?

我会理解是否传递了@ output.should_receive(:puts).with(“欢迎来到Codebreaker!”),但输出只是传递给initialize的参数。 RSpec如何知道输出实际上是@output甚至可以访问@output?

1 个答案:

答案 0 :(得分:3)

  

但是,在game.rb文件中,我们清楚地看到输出是初始化的ARGUMENT   方法

是的,这允许您的测试传递用于测试的output对象。它将在此处使用此代码保存:

def initialize(output)
  @output = output
end

那么,

  

@outputs,实例变量而不是参数参数,将“欢迎使用Codebreaker!”呼唤它。

它是同一个对象,因为initialize将作为参数传入的任何内容设置为实例变量@output。现在,每个实例方法都可以使用此实例变量。

  

为什么在明确输出未接收时,此测试通过:puts,但@output是?

因为它是同一个对象。测试将对象传入,它将保存到@output,然后最终调用puts