raise_error规范在Rspec 3.4中没有返回true

时间:2016-07-14 02:47:00

标签: ruby-on-rails ruby rspec

我有以下课程,我正在尝试编写规范:

module IntegrationError
  class Error < StandardError; end
  class BadRequest < IntegrationError::Error; end
  class LogicProblem < IntegrationError::Error; end

  def raise_logic_error!(message)
    raise IntegrationError::LogicProblem, message
  rescue => e
    Rails.logger.error e.message
    e.backtrace.each do |line|
      Rails.logger.error line if line.include?('integrations')
    end
  end

  def raise_bad_request!(message)
    raise IntegrationError::BadRequest, message
  end

  def log_bad_request!(message)
    Rails.logger.info message
  end
end

带有规范

RSpec.describe 'IntegrationError', type: :integration do
  let!(:klass) { Class.new { include IntegrationError } }

  describe '#log_bad_request!' do
    it 'logs it' do
      expect(klass.new.log_bad_request!('TESTME')).to be_truthy
    end
  end

  describe '#raise_bad_request!' do
    it 'raises it' do
      binding.pry
      expect(klass.new.raise_bad_request!('TESTME')).to raise_error 
    end
  end
end

raise_bad_request测试返回错误而不是true。任何人都有关于如何更好地写这篇文章的想法?

我正在使用Rails 4和Rspec 3.4。

2 个答案:

答案 0 :(得分:4)

如果我没记错的话,我相信你需要在提升时将期望提高一个块,就像这样:

describe '#raise_bad_request!' do
  it 'raises it' do
    binding.pry
    expect{klass.new.raise_bad_request!('TESTME')}.to raise_error 
  end
end

请参阅docs here

答案 1 :(得分:3)

对于raise_error匹配器,您需要传递一个块而不是值:

expect { klass.raise_bad_request!('TESTME') }.to raise_error

应该这样做!