RSpec:如何创建一个帮助存根方法?

我试图从我的帮助器中存取一个辅助方法:

# 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 

我试图存根current_user? 总是在我的unit testing中返回true:

 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 

但测试仍然通过(我希望它返回true)。

有没有我想念配置存根方法?

谢谢

您没有在SessionsHelper上调用该方法。 你是在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 

any_instance应该做你想要的:

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

正如@Vimsha所说,你在模块和实例之间感到困惑,这很容易做到。