2013-03-01 82 views
0

ruby​​/rspec的新手,試圖測試某個方法是否引發異常。我可能會完全錯誤地做這件事。RSpec should_receive未達到類中的方法

#require 'rspec' 

describe "TestClass" do 
    it "should raise exception when my method is called" do 
    test = Test.new 
    test.should_receive(:my_method).and_raise 
    end 
end 

class Test 
    def my_method 
    raise 
    end 
end 


rspec test.rb 
F 

Failures: 

    1) TestClass should raise exception when my method is called 
    Failure/Error: test.should_receive(:my_method).and_raise 
     (#<Test:0x007fc61c82f7c8>).my_method(any args) 
      expected: 1 time 
      received: 0 times 
    # ./test.rb:6:in `block (2 levels) in <top (required)>' 

Finished in 0.00061 seconds 
1 example, 1 failure 

Failed examples: 

rspec ./test.rb:4 # TestClass should raise exception when my method is called 

爲什麼消息收到零次?

回答

1

你的測試是錯誤的。爲了測試拋出一個異常,你會想這樣做:

it "should raise exception when my method is called" do 
    test = Test.new 
    test.should_receive(:my_method) 

    expect { 
    test.my_method 
    }.to raise_error  
end 

在這種情況下,你可能並不需要添加should_receive。通過調用my_method您確定test正在接收該方法。基本上,當你不需要模擬時你就是在嘲笑。

+0

謝謝!我看過期望引用別處。我完全誤用了should_receive。 – sclarson 2013-03-01 20:48:09

+0

@sparks yup! :D我用rspec掙扎了很長時間,你會想要爲所有存在的各種幫助者使用一個備忘單:https://gist.github.com/steveclarke/2353100 – 2013-03-01 20:50:00

0

你必須做些事情來調用該方法。如果是回調here是如何測試它們的示例。

+0

該鏈接可能對剛剛開始使用ruby/rspec的人感到困惑。 – 2013-03-01 20:49:12

相關問題