我如何为此编写rspec 3.1测试

时间:2015-10-17 02:20:25

标签: ruby rspec

如何为以下内容编写rspec测试。

传入的值是这个...... 90A14F 1.4

  def classname
    def init
      @input_colors = Array.new
    end
    def speak
      puts "enter your line of color values"
      result = STDIN.gets.chomp
      new_result = result.gsub!(/([\s])+/,':')
      @input_colors << new_result
    end
  end

如何为这个说话方法编写一个rspec 3.1测试,测试gets.chomp是否为... 90A14F 1.4

他们将获得一个实例var @input_colors == [“90A14F:1.4”]

1 个答案:

答案 0 :(得分:0)

您的示例中存在一些问题。我会改变它并修复它:

class ColorReader            # with `class` and an upcase class name
  def initialize             # not `init`
    @colors = []             # the use of `Array.new` is uncommon
  end

  def read
    puts "enter your line of color values"
    result = STDIN.gets.chomp
    new_result = result.gsub!(/([\s])+/,':')
    @colors << new_result
  end
end

然后测试看起来像这样:

describe ColorReader do
  describe '#read' do
    let(:input) { "90A14F 1.4\n" }

    subject(:color_reader) { ColorReader.new }

    before do
      allow(color_reader).to receive(:puts).and_return(nil)
      allow(STDIN).to receive(:gets).and_return(input)
    end

    it 'writes to the console' do
      color_reader.read
      expect(color_reader).to have_received(:puts).
        with("enter your line of color values").once
    end

    it 'reads from STDIN' do
      color_reader.read
      expect(STDIN).to have_received(:gets).once
    end

    it 'returns the sanitized input' do
      expect(color_reader.read).to eq(['90A14F:1.4'])
    end
  end
end

顺便说一下。我更愿意显式测试@colors数组的新值(可能带有attr_reader :colors)而不是read方法的implizit返回值。如果您有@colors的阅读器,那么最后一个规格可以更改为:

it 'adds the sanitized input to `colors`' do
  expect { 
    color_reader.read 
  }.to change { color_reader.colors }.from([]).to(['90A14F:1.4'])
end