Hi

In your example, unless you call:

```
a.validate_my_field
```

In the same test as:

```
# Note it doesn’t matter if this is `b` or `subject.b` if they are the same 
object.
expect(b).to receive(:to_s)
```

It won’t pass, as the method hasn’t been invoked in the scope.

e.g.

```
RSpec.describe “A” do
subject(:a) { A.new b: b }
let(:b) { B.new }

describe “#validate_my_field” do
it “will call to_s on B” do
expect(b).to receive(:to_s)
a.validate_my_field
end
end
end
```

Cheers
Jon Rowe
---------------------------
[email protected]
jonrowe.co.uk

On 11 October 2019 at 18:49, Mar Kim wrote:
> I have a model `A` which `belongs_to` `B`. And I'm trying to write a unit 
> test with `A` as `subject`:
>
> ```
> expect(subject.b).to receive(:to_s)
> ```
>
> Yet this spec always fails, saying that the instance of `B` did not receive 
> the message, notwithstanding I have put `binding.pry` in the actual code to 
> run and verified that `a.b.to_s` gets called.
>
> ```
> class A
> def validate_my_field
> binding.pry # this fires
> if b.to_s
> super
> end
> end
> ```
>
> I have even tried:
>
> ```
> expect(a).to receive(:b).and_return(b)
> expect(b).to receive(:to_s)
> ```
>
> And:
>
> ```
> expect_any_instance_of(b.class).to receive(:to_s)
> ```
>
> Yet all expectations for `to_s` fail. Why could this be?
>
> I'm in Rails 6 with Rspec 3.8.0.

-- 
You received this message because you are subscribed to the Google Groups 
"rspec" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rspec/dejalu-217-4f9251b3-cfd9-4472-a4ca-6aa2c973cb5e%40jonrowe.co.uk.

Reply via email to