私は RSpec Book に取り組んでおり、次のテスト コードがあります。
require 'spec_helper'
module Codebreaker
describe Game do
describe "#start" do
let(:output) { double('output').as_null_object }
let(:game) { Game.new(output) }
it "sends a welcome message" do
output.should_receive(:puts).with('Welcome to Codebreaker!')
game.start
end
it "prompts for the first guess" do
output.should_receive(:puts).with('Enter guess:')
game.start
end
end
end
end
これは次のコードに対応します。
module Codebreaker
class Game
def initialize(output)
@output = output
end
def start
@output.puts 'Welcome to Codebreaker!'
@output.puts 'Enter a guess:'
end
end
end
:output を double.as_null_object として設定したので、想定外の引数やメソッドは無視されると思います。最初のテスト (ウェルカム メッセージを送信する) では、それが実行され、合格します。ただし、2 番目のテストでは、次のエラーが表示されます。
Failure/Error: output.should_receive(:puts).with('Enter guess:')
Double "output" received :puts with unexpected arguments
expected: ("Enter guess:")
got: ("Welcome to Codebreaker!"), ("Enter a guess:")
# ./spec/codebreaker/game_spec.rb:16:in `block (3 levels) in <module:Codebreaker>'
double が "Welcome to Codebreaker!" の両方を返すのはなぜですか? 「推測を入力してください」のみを期待するように明示的に指示した場合、「推測を入力してください」、およびこの同じセットアップ/構造を維持しながらこれを修正するにはどうすればよいですか?