1

我无法理解如何使用puts. 我需要知道我需要在我的 RSPEC 文件中做什么。

这是我的 RSPEC 文件:

require 'game_io'
require 'board'


describe GameIO do
  before(:each) do
    @gameio = GameIO.new
    @board  = Board.new
  end

  context 'welcome_message' do
    it 'should display a welcome message' do
      test_in   = StringIO.new("some test input\n")
      test_out  = StringIO.new
      test_io   = GameIO.new(test_in, test_out)

      test_io.welcome_message
      test_io.game_output.string.should == "Hey, welcome to my game. Get ready to be defeated"
    end
  end

end

这是它正在测试的文件:

class GameIO
  attr_reader :game_input, :game_output
  def initialize(game_input = $stdin, game_output = $stdout)
    @stdin  = game_input
    @stdout = game_output
  end


  def welcome_message 
    output "Hey, welcome to my game. Get ready to be defeated" 
  end


  def output(msg)
    @stdout.puts msg
  end

  def input
    @stdin.gets
  end

end

注意:我更新了我的 RSPEC 代码,以反映我对测试文件所做的更改,给出了其他地方的建议。为了彻底解决这个问题,我在我的主文件中使用了 Chris Heald 建议的更改。谢谢大家,谢谢克里斯。

4

3 回答 3

2

只需检查您是否正在向其发送消息:

@gameio.should_receive(:puts).with("Hey, welcome to my game. Get ready to be defeated")
于 2013-07-17T23:09:08.373 回答
2

您的初始化程序应该是:

def initialize(game_input = $stdin, game_output = $stdout)
  @game_input  = game_input
  @game_output = game_output
end

这样做的原因是attr_accessor生成这样的方法:

# attr_accessor :game_output
def game_output
  @game_output
end

def game_output=(output)
  @game_output = output
end

(attr_reader 只生成 reader 方法)

因此,由于您从不分配@game_output,您的game_output方法将始终返回 nil。

于 2013-07-17T23:10:09.393 回答
0

你可以存根puts并打印。

也许最基本的方法是临时将 STDOUT 重新分配给一个变量,并确认该变量与您期望的输出相匹配。

Minitest 有must_output一个断言/规范。

因此,代码是:

 ##
 # Fails if stdout or stderr do not output the expected results.
 # Pass in nil if you don't care about that streams output. Pass in
 # "" if you require it to be silent. Pass in a regexp if you want
 # to pattern match.
 #
 # NOTE: this uses #capture_io, not #capture_subprocess_io.
 #
 # See also: #assert_silent

 def assert_output stdout = nil, stderr = nil
   out, err = capture_io do
     yield
   end

   err_msg = Regexp === stderr ? :assert_match : :assert_equal if stderr
   out_msg = Regexp === stdout ? :assert_match : :assert_equal if stdout

   y = send err_msg, stderr, err, "In stderr" if err_msg
   x = send out_msg, stdout, out, "In stdout" if out_msg

   (!stdout || x) && (!stderr || y)
 end
于 2013-07-17T23:16:50.440 回答