Rspec-mocks doesn't raise the exception

2.3k Views Asked by At

I have this piece of RoR code that creates a gitlab repository. If the repository already exists, the method returns false with the error message.

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

```

I would like to test this method, in particular when the repository already exists. I use rspec-mocks and this is what I have:

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

The test returns true. It seems like the exception is not triggered.

Any idea what's going on ?

2

There are 2 best solutions below

0
Yann PRONO On BEST ANSWER

In fact, the issue was the initialization of the Gitlab::Error::BadRequest object.

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

```

1
Mugur 'Bud' Chirica On

You need to use a block when checking for exceptions.

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

Try and update the code to match your needs.

More info can be found here: https://relishapp.com/rspec/rspec-expectations/docs/built-in-matchers/raise-error-matcher