AJFaraday
AJFaraday

Reputation: 2450

Rspec expectation error: reading hash argument as keyword arguments

I'm in the middle of an update to Rails 7.1.3 and I've run into an interesting issue.

I have an initialize which has one positional argument (which defaults to an empty hash) and some keyword arguments: eg.

  def initialize(opts = {}, foo: :bar)

And I'm mocking out the initialize with just the options hash in my specs:

  options = {cow: "over", moon: "under"}
  expect(Thing).to(receive(:new).with(options))

This results in an unexpected argument error, where it appears the members of the options hash have been read as keyword arguments:

RSpec::Mocks::MockExpectationError: Invalid keyword arguments provided: cow, moon

How can I make this mock read the hash as a hash in the position of the first argument?


Minimal case to reproduce:

class Thing
  def initialize(opts = {}, foo: "bar")
  end
end

require "rspec"

describe Thing do
  let(:options) { {cow: "over", moon: "below"} }

  it "mocks out the initialize" do
    expect(Thing).to(receive(:new).with(options))

    pp Thing.new(options)
  end
end

And versions of my rspec-related gems:

rails (7.1.3)
rspec (3.13.0)
rspec-core (3.13.0)
rspec-expectations (3.13.0)
rspec-mocks (3.13.0)
rspec-rails (6.1.0
rspec-retry (0.6.2)
rspec-support (3.13.0)

Edit: Things I've tried:

Upvotes: 0

Views: 200

Answers (0)

Related Questions