RSpec: How to create an auxiliary stub method?

I am trying to drown out a helper method from my helper:

# sessions_helper.rb
require 'rest_client'

module SessionsHelper
  BASE_URL = "http://localhost:1234"

  def current_user?(token)
    sessions_url = BASE_URL + "/sessions"
    headers = {"X-AuthToken" => 12345}

    begin
      RestClient.get(sessions_url, headers)
      return true
    rescue RestClient::BadRequest
      return false
    end
  end

end

Am I trying to drown current_user? always return true in my unit test:

require 'spec_helper'

describe SessionsHelper do
  it "Should not get current user with random token" do
    SessionsHelper.stub(:current_user?).and_return(true)
    expect(current_user?(12345)).to eq(false)
  end
end

But the test still passes (I expect it to return true).

Is there something I skipped to set up a stub method?

thank

+4
source share
2 answers

You do not call the method on SessionsHelper. You call him on self. Therefore, try to impose the method on yourself.

describe SessionsHelper do
  it "Should not get current user with random token" do
    stub(:current_user?).and_return(true)
    expect(current_user?(12345)).to eq(false)
  end
end
0
source

any_instance should do what you want:

SessionsHelper.any_instance.stub(:current_user?).and_return(true)

As @Vimsha says, you are confused between the module and the instance, which is easy to do.

0
source

All Articles