Search code examples
ruby-on-railstestingrspecwebmock

Rails: How to stub and test this external service call?


Hello I have something like the following code inside a rails model:

class Page < ActiveRecord::Base
  def calculate_page_speed(url)
    browser = Watir::Browser.new :phantomjs
    start = Time.now
    browser.goto url
    finish = Time.now
    self.speed = finish - start
  end
end

Here is the test:

describe Page do
  context "calculate_page_speed for Page" do
    let(:google) { FactoryGirl.create(:page, url: "http://www.google.com") }

    it "should set the page speed" do
      google.speed.should be_nil
      google.calculate_page_speed
      google.speed.should_not be_nil
    end
  end
end

How can I stub effectively the external service for not calling it during the test?


Solution

  • There is an approach like:

    class Page < ActiveRecord::Base
      def calculate_page_speed(url)
        start = Time.now
        browser.goto url
        finish = Time.now
        self.speed = finish - start
      end
    
      def browser
        @browser ||= Rails.env.test? ? FakeBrowser.new : Watir.new(:phantomjs)
      end
    
      class FakeBrowser
        def goto
        end
      end 
    end
    

    but here you have test code in prod code which is not great.


    A derived solution would be to inject the expected browser class in a config.


    Finally you can just stub stuff:

    Watir::Browser.any_instance.stub(:goto)