2012-12-26 51 views
3

我寫了一個測試,我期望結果拋出一個錯誤。寫rspec來測試錯誤,但錯誤被拋出,並停止測試傳遞

it{ Authentication.create_with_omniauth!(nil, nil).should raise_error } 

結果確實會引發錯誤,但驗證失敗。顯然這是拋出一個錯誤。 :)

2) Authentication methods: self.create_with_omniauth!: with bad input 
    Failure/Error: it{ Authentication.create_with_omniauth!(nil, nil).should raise_error } 
    ArgumentError: 
     ArgumentError 
    # ./app/models/authentication.rb:13:in `create_with_omniauth!' 
    # ./spec/models/authentication_spec.rb:69:in `block (5 levels) in <top (required)>' 

現在是什麼?你如何測試一個錯誤?

回答

3

您應該使用期待{}。要raise_error語法

expect { Authentication.create_with_omniauth!(nil, nil) }.to raise_error 

lambda { Authentication.create_with_omniauth!(nil, nil) }.should raise_error 
如果使用Rspec的1.XX

退房文檔

https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher#expect-any-error

http://rspec.rubyforge.org/rspec/1.2.9/classes/Spec/Matchers.html#M000176

+0

嗯...我立即得到了'遇到例外情況:#>'我只把自己擁有獨自'形容‘壞輸入’嗎 expect {Authentication.create_with_omniauth!(nil,nil)} .to raise_error end' – TLK

+0

您使用的是什麼版本的Rspec? 新的語法https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher#expect-any-error 舊的一個http://rspec.rubyforge。 org/rspec/1.2.9/classes/Spec/Matchers.html#M000176 –

+1

謝謝我找出問題所在。對於像我這樣的新手來說,你可能希望修改你的答案來指定'expect'需要在'it'塊內。愚蠢的錯誤,但我沒有認識到這個問題。 – TLK

0

我不跟omniauth經驗豐富,但確實是這樣的工作?

describe "authentication" do 
    context "when nil" do 
    let(:nil_authentication) { Authentication.create_with_omniauth!(nil, nil) } 
    subject { -> { nil_authentication } } 
    it { should raise_error } 
    end 
end