【问题标题】:RSpec Book example confusion (should_receive)RSpec Book 示例混淆 (should_receive)
【发布时间】:2014-05-12 23:33:09
【问题描述】:

我现在正在尝试遵循 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 文件中,我们清楚地看到输出是初始化方法的参数。 @outputs,实例变量而不是参数参数,有“欢迎使用 Codebreaker!”叫它。为什么当明显输出没有接收到:puts,但@output 接收到时,这个测试应该通过?

如果 @output.should_receive(:puts).with("Welcome to Codebreaker!") 传递,我会理解,但输出只是传递给初始化的参数。 RSpec 如何知道输出实际上是@output 甚至可以访问@output?

【问题讨论】:

    标签: ruby-on-rails ruby rspec bdd


    【解决方案1】:

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

    是的,这允许您的测试通过为测试而设计的output 对象。它在这里与此代码一起保存:

    def initialize(output)
      @output = output
    end
    

    那么,

    @outputs,实例变量而不是实参参数,有 puts "Welcome to Codebreaker!"呼唤它。

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

    当明显输出没有接收到:puts,但@output 接收到时,为什么这个测试应该通过?

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

    【讨论】:

      猜你喜欢
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      相关资源
      最近更新 更多