← Back to Upcase

Rspec spy method

Before I ask my question: Thank you all very much for making Upcase such a great service. I’ve learned so much already and have definitely leveled up my testing skills as a result. Thank you!

I just read https://robots.thoughtbot.com/a-closer-look-at-test-spies a few different times and noticed the reference to this video, which I’ve watched a few times: https://thoughtbot.com/upcase/videos/stubs-mocks-spies-and-fakes. The video references spies but doesn’t use Rspec’s spy method. Also, the post on the blog doesn’t use the spy method in context (I don’t see the entire test, just the one line change). From the blog post, is this the correct use of spy?

describe "updating credit card details" do
  it "saves the credit card with Stripe" do
    stripe_customer = spy("Stripe::Customer")
    token = "fake token"

    post :update, stripe_token: token

    expect(stripe_customer).to have_received(:card=).with(token)
    expect(stripe_customer).to have_received(:save)
  end
end

The spy method is fairly recent addition to RSpec (Sep 2014). It’s always been possible to use a spy approach, the new method just makes the code a little more intention-revealing.

The usage of spy in your code example looks correct.

Thanks for getting back to me, Andy, and for some more background in spy. I now need to go through some personal projects and clean up the tests a bit!