【问题标题】:Rspec-mocks doesn't raise the exceptionRspec-mocks 不会引发异常
【发布时间】:2018-09-06 14:04:52
【问题描述】:

我有这段创建 gitlab 存储库的 RoR 代码。如果存储库已存在,则该方法返回 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。好像没有触发异常。

知道发生了什么吗?

【问题讨论】:

  • allow(GitLab) 更改为expect(GitLab) 会发生什么?

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


【解决方案1】:

检查异常时需要使用块。

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

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

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

【讨论】:

  • 我知道,这里的问题是我无法模拟会引发异常的函数。
【解决方案2】:

事实上,问题在于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

```

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多