简体   繁体   English

Rspec-从构造函数中抽出gets.chomp

[英]Rspec - Stubbing gets.chomp out of the constructor

I'm writing a Mastermind game in Ruby and in the constructor of the class 'Game' I want to use gets.chomp to ask the user for its name. 我正在用Ruby和“游戏”类的构造函数中编写Mastermind游戏,我想使用gets.chomp来询问用户名字。 Pretty easy, but where I run into trouble is when testing this class in RSpec, but I can't seem to properly stub out 'gets' and 'puts', because they are in the constructor not a regular method. 相当容易,但是遇到麻烦的是在RSpec中测试该类时,但是我似乎无法正确地存入“ gets”和“ puts”,因为它们在构造函数中不是常规方法。

class Game
  def initialize
    puts "Please enter your name:"
    @player = Player.new(gets.chomp)
  end
end

describe Game do
  Game.stub(:gets).and_return("Create Code AI")
  Game.stub(:puts)
  subject(:game) { Game.new }

  describe "#new" do
    its("player.name") { eql("Create Code AI") }
  end
end

class Player
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

I've also tried putting the stubs into 'before' and 'let' blocks amongst other things, but nothing seems to work. 我还尝试过将存根放入“ before”和“ let”块中,但似乎没有任何效果。 Any help is appreciated! 任何帮助表示赞赏!

I have a method which captures stdin and stdout to help with the testing in cases like these: 我有一种捕获stdin和stdout的方法,可以在以下情况下进行测试:

require 'stringio'

module Kernel
  def capture_stdout(console_input = '')
    $stdin = StringIO.new(console_input)
    out = StringIO.new
    $stdout = out
    yield
    return out.string.strip
  ensure
    $stdout = STDOUT
    $stdin = STDIN
  end
end

Now, let's assume I want to test a method that interacts with stdin/stdout: 现在,假设我要测试与stdin / stdout交互的方法:

def greet
  name = gets
  puts "Welcome, #{name}!"
end

I would write the following test: 我将编写以下测试:

require 'rspec/autorun'

RSpec.describe '#say_name' do
  it 'prints name correctly' do
    input = 'Joe'
    result = capture_stdout(input) do
      greet
    end

    expect(result).to eql 'Welcome, Joe!'
  end
end

I presented the example above to illustrate how to test both console input and output. 我提供了上面的示例,以说明如何测试控制台输入和输出。

In your case, the test could look like this: 在您的情况下,测试可能如下所示:

describe Game do
  subject(:game) do
    capture_stdout('Create Code AI') { return Game.new }
  end

  describe "#new" do
    its("player.name") { eql("Create Code AI") }
  end
end

Note: In order for this to work, #player should be an accessible member of Game . 注意:为了#player起作用, #player应该是Game的可访问成员。 So, you may want to add this to your Game class: 因此,您可能需要将此添加到您的Game类中:

attr_reader :player

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM