2015-10-17 172 views
0

如何爲以下內容編寫rspec測試?如何爲此編寫rspec 3.1測試

是獲取這是傳遞的值... 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」]

回答

0

您的示例中存在一些問題。順便說一句

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 

:我喜歡這種改變,並修復它的東西:

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 

然後在測試看起來是這樣的。我寧願明確測試@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