Read more

RSpec 3 argument constraints use weak equality

Tobias Kraze
February 17, 2016Software engineer at makandra GmbH

If you expect method calls in RSpec 3, be aware that the argument matchers use very liberal equality rules (more like === instead of ==).

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

For example:

expect(subject).to receive(:foo).with(MyClass)

subject.foo(MyClass)      # satisfies the expectation
subject.foo(MyClass.new)  # also satisfies the expectation

expect(subject).to receive(:bar).with(/regex/)

subject.bar(/regex/)      # satisfies the expectation
subject.bar('regex')      # also satisfies the expectation

This is usually not an issue, except when your method arguments are things like classes, regexps or ranges.

If you want to expect strict equality, you could use

expect(subject).to receive(:foo).with(eq(MyClass))

or

expect(subject).to receive(:foo) do |klass|
  expect(klass).to eq MyClass
end
Posted by Tobias Kraze to makandra dev (2016-02-17 14:34)