2012-05-13 57 views
0

‘重器’紅寶石rspec的錯誤「預期:1獲得:#<PROC:0x000000019155b8 @ /家

試圖讓使用存根的竅門,但我不能保證格式沒有錯誤,做什麼?我已經錯了,我知道我已經有方法,在這種情況下的代碼,但我想學習如何正確地做一個存根

測試:

describe "Convert Pounds to Kilograms" do 

it "should convert 3lb to 1kg" do 
    weight = WeightConverter.stub!(:convert).with(3, 'lbs_to_kgs').and_return(1) 
    weight.should == 1 
end 

代碼:

class WeightConverter 

    def self.convert(from, what_to_what) 
    if what_to_what == 'lbs_to_kgs' 
     (from/2.2).truncate 
    elsif what_to_what == 'kgs_to_lbs' 
     (from * 2.2).truncate 
    end 
    end 
end 

僅供參考 - 這工作(無存根)

it "should convert 91lbs to 41kgs" do 
    weight = WeightConverter.convert(91, 'lbs_to_kgs') 
    weight.should == 41 
    end 

錯誤:

失敗:

1) Convert Pounds to Kilograms should convert 3lb to 1kg 
    Failure/Error: weight.should == 1 
     expected: 1 
      got: #<Proc:[email protected]/home/durrantm/.rvm/gems/ruby-1.9.3-p125/gems/rspec-mocks-2.10.1/lib/rspec/mocks/message_expectation.rb:459 (lambda)> (using ==) 
    # ./weight_converter_spec.rb:19:in `block (2 levels) in <top (required)>' 

Finished in 0.00513 seconds 
7 examples, 1 failure 
+0

當比較浮動,你應該使用'be_close'。 – echristopherson

回答

2

你不想分配到存根,而應該像這樣做:

it "should convert 3lb to 1kg" do 
    WeightConverter.stub!(:convert).with(3, 'lbs_to_kgs').and_return(1) 
    weight = WeightConverter.convert(3, 'lbs_to_kgs') 
    weight.should == 1 
end 

然而,這是一個相當無用的測試 - 這是測試的唯一的事情就是你的存根/模擬庫做什麼它應該(即它根本沒有真正測試WeightConverter)。由於您直接測試WeightConverter的內部,所以您不需要對它進行存根。你應該使用第二個例子中的實際值。但是,如果WeightConverter依賴於另一個類,則可能會存儲其他類。

+0

是的,它是爲了學習目的如何做存根,我假裝該方法尚不存在,而且在現實中,我會做'其他的東西'不只是檢查這個返回值。因此,考慮到具有實際的WeightConverter.convert方法是我目前想要避免的。 – junky

+0

是的,那麼我給你的代碼應該爲此工作 - 它永遠不會實際調用'WeightConverter.convert',因爲它只是使用存根。 –

+0

嗯,所以一旦你將該方法定義爲存根,那麼當你調用它(實際方法)時,調用使用存根方法?所以這總是一個兩步的過程呢? – junky