RSpec 在预期会引发错误之前遇到代码错误

RSpec hits an error in code, before it is able to expect an error to be raised

这是我以前在使用 RSpec Rails 时看到的东西,我相信我知道发生了什么,我只是不知道如何解决它。

对我来说,似乎应该通过以下测试。它期待一个错误,并且引发了一个错误,尽管我假设错误的来源是它被绊倒的原因。

csv_file_spec.rb

require 'spec_helper'

RSpec.describe Cleaner::CSVFile do
  context 'when CSV file does not exist' do
    let(:file) { Cleaner::CSVFile.new('tmp/file-does-not-exist.csv') }

    it 'raises error' do
      expect(file).to raise_error
    end
  end
end

csv_file.rb

module Cleaner
  # A CSVFile is a CSV file loaded into memory. It exposes the clean method.
  class CSVFile
    attr_accessor :raw

    def initialize(file)
      @raw = File.open(file)
    end
  end
end

输出

  1) Cleaner::CSVFile is not valid
     Failure/Error: expect(Cleaner::CSVFile.new('tmp/file-does-not-exist.csv')).to raise_error
     Errno::ENOENT:
       No such file or directory @ rb_sysopen - tmp/file-does-not-exist.csv
     # ./lib/cleaner/csv_file.rb:8:in `initialize'
     # ./lib/cleaner/csv_file.rb:8:in `open'
     # ./lib/cleaner/csv_file.rb:8:in `initialize'
     # ./spec/csv_file_spec.rb:7:in `new'
     # ./spec/csv_file_spec.rb:7:in `block (2 levels) in <top (required)>'

我看到 CSVFile 对象无法初始化,因为该文件不存在,这就是 RSpesc 无法继续测试的原因,但我能做些什么来解决这个问题?

我感觉我的测试方法存在一些我没有发现的根本错误。我宁愿将错误委托给标准 File 类,而不是提出我自己的错误消息,因为错误已经足够冗长了,我只会重复工作——我应该自己实现吗?

谢谢!

For exceptions you should use block or lambda in expect syntax:

it 'raises error' do
   expect{ Cleaner::CSVFile.new('tmp/file-not-exist.csv') }.to raise_error
end

您也可以使用 stubbing :

require 'spec_helper'

RSpec.describe Cleaner::CSVFile do
  context 'when CSV file does not exist' do
    it 'raises error' do
      allow(described_class).to receive(:new).and_raise("File not exist")
      expect { described_class.new }.to raise_error("File not exist")
    end
  end
end

阅读match message with a string