Rspec: How to use expect to receive with a resource which does not exist yet?
<p>In an action called via a post request I'm creating a resource call <code>RequestOffer</code> and send an email with <code>ActionMailer</code> using the created resource as a parameter:</p>

<pre><code>@request_offer = RequestOffer.new(request_offer_params)
if @request_offer.save
    RequestOfferMailer.email_team(@request_offer).deliver_later
end
</code></pre>

<p>When my controller spec, I want to test that my <code>RequestOfferMailer</code> is called using the method <code>email_team</code> with the resource <code>@request_offer</code> as a parameter.</p>

<p>When I want to user <code>expect(XXX).to receive(YYY).with(ZZZ)</code>, the only way I found was to declare my expectation before making the POST request. However, <code>ZZZ</code> is created by this <code>POST</code> request, so I have no way to set my expectation before.</p>

<pre><code># Set expectation first
message_delivery = instance_double(ActionMailer::MessageDelivery)

# ZZZ used in .with() does not exist yet, so it won't work
expect(RequestOfferMailer).to receive(:email_team).with(ZZZ).and_return(message_delivery)
expect(message_delivery).to receive(:deliver_later)

# Make POST request that will create ZZZ
post :create, params
</code></pre>

<p>Any idea how to solve this problem?</p>