4

I'm trying to test out that a method gets called with a custom Ruby object as an argument, and that that object has the correct attribute.

This is working right now:

expect(MyClass).to receive(:a_method).with(instance_of(SomeObject))

but I can't find anything about how to test the internals of SomeObject

I want something like:

expect(MyClass).to receive(:a_method).with(instance_of(SomeObject)).with_attribute(:name => "Bob")

but this throws a NoMethodError

  • 1
    it should not matter how SomeObject is defined, since you're testing that the method is getting called. In theory, there should be a spec for `:a_method` in `MyClass` specs that exercises what you're trying to solve here – mr_sudaca Nov 30 '16 at 22:08
  • Thanks for your comment. Do you mean that I shouldn't test the inner workings of `SomeObject` when testing `:a_method`? In my particular circumstance, `MyClass::some_other_method` gets called with different parameters. `:some_method` always ends up getting called with SomeObject as an argument when I test :some_other_method, but depending on those parameters `:some_other_method` gets called with, the attributes in SomeObject change. – user3230279 Nov 30 '16 at 22:54
  • 1
    yeah, `SomeObject` inner stuff is not relevant here, but, I think it's right to expect an instance of that class. – mr_sudaca Dec 01 '16 at 00:56
  • gotcha thanks. I think there might be a better way about it. :) – user3230279 Dec 01 '16 at 01:05

1 Answers1

-1

from rspec 3.1, you could use have-attributes-matcher to do that.

expect(object).to receive(:foo)
.with(have_attributes(first_name: 'Hans', last_name: 'Dampf'))

There's case that this will be failed: when the argument objects are Comparable objects, in that case you could check the specific attribute object_id or using the an_object_equal_to matcher, reference.

Lam Phan
  • 3,405
  • 2
  • 9
  • 20