Rspec raise_error 在上下文中似乎不起作用

Rspec raise_error within context doesn't seem to work

我写了这个,它通过了。

it 'raises a GitConfigNotFound error when YAML config file cannot be found' do
    allow(YAML).to receive(:load_file)
                   .with(Rails.root.join('config', 'git_config.yml'))
                   .and_raise(Errno::ENOENT)
    expect { described_class::config }.to raise_error GitConfigNotFound
end

然后我试图将它放在一个上下文中以匹配我的其他测试,但它失败了。我格式化如下所示。有没有人知道为什么会这样?

context 'will raise a GitConfigNotFound exception if git config file is missing' do
    before do
      allow(YAML).to receive(:load_file)
                         .with(Rails.root.join('config', 'git_config.yml'))
                         .and_raise(Errno::ENOENT)
    end
    it { expect(described_class::config).to raise_error GitConfigNotFound }
  end

它给了我这个输出,这似乎是我想要的,但由于某种原因没有捕捉到它。:

  1) GitConfigsLoader will raise a GitConfigNotFound exception if git config file is missing 
     Failure/Error: it { expect(described_class::config).to raise_error }
     GitConfigNotFound:
      Error: git_config.yml not found.
     # ./lib/git_configs_loader.rb:9:in `rescue in config'
     # ./lib/git_configs_loader.rb:7:in `config'
     # ./spec/lib/git_configs_loader_spec.rb:37:in `block (3 levels) in <top (required)>'

也许这就是@PeterAlfvin 的意思,但我终于根据他的另一个答案找到了答案!我使用的是 expect(...) 而不是 expect{...}。 parens 立即执行并立即爆炸并且没有被 .to raise_exception 捕获。使用大括号允许 raise_error 执行 except 块并捕获错误。

context 'when no git_config.yml file is proivded' do
   before do
    allow(YAML).to receive(:load_file).and_raise(Errno::ENOENT)
   end
   it { expect{ described_class::config }.to raise_exception GitConfigNotFound }
end