How would I test that the initialize method called some function?

11 views
Skip to first unread message

Blaine Lafreniere

unread,
Apr 20, 2023, 3:49:56 AM4/20/23
to rspec
I'm trying to test that the subject has called get_auth_token, but I don't think I can do that the way I have my code written.

From what I understand, I'm supposed to have a test spy set up before actually calling the code I'm testing, to sort of record/observe which methods are called on the spy object.

I guess that is complicated by the fact that my subject is defined as Yotpo::BackendApi.new

So I guess my question is, how would you set any expectations on the instance before the instance even exists yet? Or would this indicate that I have a code smell, and I need to re-think my design?

RSpec.describe Yotpo::BackendApi do
  subject { Yotpo::BackendApi.new }

  describe 'class constants' do
    it 'has STORE_ID' do
      expect(described_class).to have_constant(:STORE_ID)
    end

    it 'has CLIENT_SECRET' do
      expect(described_class).to have_constant(:CLIENT_SECRET)
    end
  end

  describe '::new' do
    it 'calls #get_auth_token' do
      expect(subject).to have_received(:get_auth_token)
    end
  end
end

Jon Rowe

unread,
Apr 20, 2023, 3:56:03 AM4/20/23
to Zach Hamman
Hi!

If `#get_auth_token` is a method on your class under test called in `#initialize`, then you should not write an expectation on that, but instead on what it does. If it’s on a 3rd party object, you could pass in a spy, or create a spy via an expectation on its `.new` or other constructor method.

Generally speaking you should not mock/stub/spy on methods within the class under test as this is definietly a “test smell”, when you do so the tests become the equivalent of “calling this method calls this method” which is not a useful test, instead test what it actually does (its behaviour).

Cheers
Jon
--
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 rspec+un...@googlegroups.com.

Reply all
Reply to author
Forward
0 new messages