【问题标题】:RSpec test for a method that contains gets.chomp包含gets.chomp的方法的RSpec测试
【发布时间】:2015-03-28 23:21:07
【问题描述】:

如何设计 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

【问题讨论】:

    标签: ruby rspec


    【解决方案1】:

    您可以为此使用存根/模拟。但主要问题是:你把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
    

    【讨论】:

    猜你喜欢
    • 2020-09-25
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    相关资源
    最近更新 更多