Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub a method that is called in initialize method

Tags:

ruby

rspec

I want to stub a method that is called in initialize method.

There is a class Company like this:

class Company
  def initialize(code: code, driver: driver)
    @driver = driver
    @code = code
    navigate_to_search_result        
  end

  def navigate_to_search_result
    # do something
  end
end

And I want to stub the method navigate_to_search_result.

before(:each) do
  company = Company.new(code: 7220, driver: Selenium::WebDriver.for(:phantomjs))
  allow(company).to receive(:navigate_to_search_result){ true }  
end

But this code fails because navigate_to_search_result is already executed by initializing.

How can I stub method like this?

like image 627
ironsand Avatar asked Jan 09 '23 18:01

ironsand


1 Answers

One of the following lines should be present/run in your test before you instantiate a Company object i.e. before you do Company.new.

allow_any_instance_of(Company).to receive(:navigate_to_search_result){ true }

or

allow_any_instance_of(Company).to receive(:navigate_to_search_result).and_return(true)
like image 52
SHS Avatar answered Jan 18 '23 01:01

SHS