jeudi 23 juillet 2015

Asserting argument of multiple calls in RSpec 3

I need to make assertion on whether a code path would log a particular event.

Suppose in my code:

Logging::Tracking.logger.log_event(event_name: 'some event')
Logging::Tracking.logger.log_event(event_name: 'some other event')
Logging::Tracking.logger.log_event(
  event_name: 'cool_event',
  event_data: { request_id: @request.id, user_id: @user.id }
)

in spec:

allow(Logging::Tracking.logger).to receive(:log_event)
expect(Logging::Tracking.logger).to receive(:log_event) do |params|
  expect(params[:event_name]).to eq('cool_event')
  expect(params[:event_data][:request_id]).to eq(@request.id)
  expect(params[:event_data][:user_id]).to eq(@user.id)
end

This assertion would be valid in RSpec 2, however, in RSpec 3, the test would fail with:

Failure/Error: expect(params[:event_name]).to eq('cool_event')

  expected: "cool_event"
  got: "some event"

  (compared using ==)

One solution would be to make a mock logger object which stores all the received calls in memory, then assert whether the event exists in the received calls. However, I'm interested to see whether there is a way to do it with just RSpec assertions.

Thank you,

Aucun commentaire:

Enregistrer un commentaire