Rspec-模拟不会引发异常

Rspec-mocks doesn't raise the exception

我有一段创建 gitlab 存储库的 RoR 代码。如果存储库已经存在,则方法 returns false 并显示错误消息。

class CreateRepositoryJob < ApplicationJob
  queue_as :default

  def perform(id)
    namespace = Gitlab.create_group("applications", "applications")        
    begin
      repo = Gitlab.create_project(id, namespace_id: namespace.id).to_hash.symbolize_keys
      [true, repo]
    rescue Gitlab::Error::BadRequest => e
      [false, e]
    end
  end
end

```

我想测试这个方法,特别是当存储库已经存在时。我使用 rspec-mocks,这就是我所拥有的:

it "cannot be created because the repository already exists" do
   # some mocks...
   allow(Gitlab).to receive(:create_project).with(anything).and_raise(Gitlab::Error::BadRequest)
   added, repo = CreateRepositoryJob.perform_now entity, entity_directory
   expect(added).to be false
end

测试returns正确。好像没有触发异常。

知道发生了什么吗?

检查异常时需要使用块。

expect { added }.to raise_error(Gitlab::Error::BadRequest)

尝试更新代码以满足您的需要。

可在此处找到更多信息:https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher

事实上,问题是 Gitlab::Error::BadRequest 对象 的初始化。

it "raise an exception for the second repository" do
  # some mocks...
  allow(Gitlab).to receive(:create_project).with(anything, anything).and_raise(Gitlab::Error::BadRequest.new(double(parsed_response: "error", code: 404, request: request)))
  added, _ = CreateRepositoryJob.perform_now  entity, entity_directory
  expect(added).to be false
end

```