【问题标题】:RSpec: How to create a helper stub method?RSpec:如何创建辅助存根方法?
【发布时间】:2014-07-28 18:29:53
【问题描述】:

我正在尝试从我的助手中存根一个助手方法:

# 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?在我的单元测试中始终返回 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)。

配置存根方法有什么我想念的吗?

谢谢

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    您没有调用SessionsHelper 上的方法。您在self 上调用它。所以尝试在 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
    

    【讨论】:

    • 谢谢,但现在我得到了这个错误:Failure/Error: stub(:current_user?).and_return(true) Stub :current_user?收到意外消息:and_return with (true)
    【解决方案2】:

    any_instance 应该做你想做的事:

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

    正如@Vimsha 所说,您对模块和实例感到困惑,这很容易做到。

    【讨论】:

    • 我收到此错误:SessionsHelper:Module 的未定义方法“any_instance”。我正在使用 rails-rspec 和 rails 4.0
    • 嗯,你可以试试allow 建议here
    猜你喜欢
    • 2012-05-19
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多