RSpec测试包含gets.chomp的方法

时间:2015-03-28 23:21:08

标签: ruby rspec

如何设计RSpec测试以将gets.chomp方法分配给实例变量?

def choose
    puts "Please enter the type you want:"
    @type = gets.chomp
    puts "Thank you, now please enter how many of those you want:"
    @quantity = gets.chomp
end

1 个答案:

答案 0 :(得分:2)

您可以使用存根/模拟。但主要问题是:你在哪里放置def choose?这很重要,因为我会将它调用于某个对象。

假设您在class Item中使用此方法:

class Item
  def choose
    puts "Please enter the type you want:"
    @type = gets.chomp
    puts "Thank you, now please enter how many of those you want:"
    @quantity = gets.chomp
  end
end

然后我将能够存根getschomp来模拟用户的输入:

RSpec.describe Item do
  describe '#choose' do
    before do
      io_obj = double
      expect(subject)
        .to receive(:gets)
        .and_return(io_obj)
        .twice
      expect(io_obj)
        .to receive(:chomp)
        .and_return(:type)
      expect(io_obj)
        .to receive(:chomp)
        .and_return(:quantity)
    end

    it 'sets @type and @quantity according to user\'s input' do
      subject.choose

      expect(subject.instance_variable_get(:@type)).to eq :type
      expect(subject.instance_variable_get(:@quantity)).to eq :quantity
    end
  end
end