Rspec-mocks不会引发异常

时间:2018-09-06 14:04:52

标签: ruby-on-rails rspec rspec-mocks

我有一段RoR代码,用于创建gitlab存储库。如果存储库已经存在,则该方法返回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

测试返回 true 。似乎没有触发异常。

知道发生了什么吗?

2 个答案:

答案 0 :(得分:0)

检查异常时需要使用块。

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

尝试并更新代码以符合您的需求。

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

答案 1 :(得分:0)

实际上,问题出在 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

```