【问题标题】:Rspec Error: undefined local variable or method `cookies' for #<RSpec::ExampleGroups...etcRspec 错误:#<RSpec::ExampleGroups...等的未定义局部变量或方法“cookies”
【发布时间】:2014-09-24 05:25:15
【问题描述】:

我和其他人一样,有一个应用程序的行为会根据用户是否登录而有所不同。我无法通过我的 SessionsHelper 登录用户,因为 Rspec 似乎没有定义“cookies”变量。 这是我的带有相关代码的 SessionsHelper 模块:

module SessionsHelper

  def sign_in user
    cookies.permanent[:remember_token] = user.remember_token
    self.current_user = user
  end

end

这是我的规范中的代码:

require 'rails_helper'

include SessionsHelper

describe "Topic#create features" do
  let(:user) { FactoryGirl.create(:user) }

  before do
    visit topics_path
  end
end

context "when user is logged in" do
  before do
    sign_in user
    visit current_path
  end


 // Some tests written here

end

以下是我收到的错误:

未定义的局部变量或方法 `cookies' for #

发生了什么事?

【问题讨论】:

    标签: ruby-on-rails ruby cookies rspec capybara


    【解决方案1】:

    虽然 Zoinks10 的答案是正确的,但遗憾的是它不能满足我的需求(除非我做错了什么)。

    我发现一个不错的解决方法是在规范文件夹中创建一个支持目录(此文件夹中的任何文件都将自动加载到您的规范中,因此将其命名为“支持”很好)。

    然后我编写了导航页面和通过 capy_bara 登录的实际函数:

    // spec/support/utilities.rb
    
    include ApplicationHelper    
    
    def sign_in(user)
      visit signin_path
      fill_in "Email",    with: user.email
      fill_in "Password", with: user.password
      click_button "Sign in"
    end
    

    现在我想起来似乎很明显 - 希望它可以帮助任何因这个问题而遇到障碍的人

    【讨论】:

      【解决方案2】:

      cookie 哈希仅在 RSpec 的控制器测试中可用。您可以通过将 type: :request 添加到您的上下文来告诉您的规范假装它们是控制器规范,如下所示:

      describe 'something that requires cookies', type: :request do
      it { expect(cookies[:remember_token]).to be_nil } // now the variable is defined as nil.
      end
      

      【讨论】:

      • 谢谢,但问题仍然存在,因为我正在尝试执行功能测试。通过将其设为 type: :request,我将无法访问诸如“visit example_path”之类的功能测试功能。我可以很容易地测试我的登录功能在控制器测试中是否有效,问题是我不能两者都做。我无法在我的功能测试中登录,因此我无法测试一项功能,例如填写仅供登录用户使用的表单。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多