编写rspec来测试错误,但抛出错误并停止测试通过

时间:2012-12-26 17:11:46

标签: ruby-on-rails error-handling 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)>'

现在怎样?你如何测试错误?

2 个答案:

答案 0 :(得分:3)

您应该使用 expect {}。raise_error 语法

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

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

如果您使用Rspec 1.X.X

查看文档

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 :(得分: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