6

I am trying to stub 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

I try to stub the current_user? to 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 pass (I expect it returns true instead).

Is there something I miss to configure the stub method?

Thanks

Kintarō
  • 2,947
  • 10
  • 48
  • 75

2 Answers2

0

You are not calling the method on SessionsHelper. You are calling it on self. So try stubbing the method on self.

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
usha
  • 28,973
  • 5
  • 72
  • 93
  • 1
    Thanks but now I got this error:Failure/Error: stub(:current_user?).and_return(true) Stub :current_user? received unexpected message :and_return with (true) – Kintarō Jul 28 '14 at 18:37
0

any_instance should do what you want:

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

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

Hew Wolff
  • 1,489
  • 8
  • 17
  • 1
    I got this error: undefined method `any_instance' for SessionsHelper:Module. I am using rails-rspec and rails 4.0 – Kintarō Jul 28 '14 at 18:39
  • Hmm, you might try `allow` as suggested [here](http://stackoverflow.com/questions/22373018/how-to-remove-deprecation-stub-is-deprecated-use-stub-instead-message). – Hew Wolff Jul 28 '14 at 18:51