【问题标题】:Writing rspec to test for error, but error is thrown and stops test from passing编写 rspec 以测试错误,但抛出错误并阻止测试通过
【发布时间】:2012-12-12 04:47:51
【问题描述】:

我写了一个测试,我希望结果会抛出一个错误。

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)>'

现在呢?如何测试错误?

【问题讨论】:

    标签: ruby-on-rails error-handling rspec


    【解决方案1】:

    我没有使用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
    

    【讨论】:

      【解决方案2】:

      你应该使用expect {}.to 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

      【讨论】:

      • 嗯...我立即得到了Exception encountered: #&lt;NoMethodError: undefined method expect' 的#<0x007fbe9e1f4028>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 2017-01-01
      相关资源
      最近更新 更多