【问题标题】:undefined method `permanent' when attempting to create a cookie尝试创建 cookie 时未定义的方法“永久”
【发布时间】:2014-02-01 20:41:50
【问题描述】:

我创建了一个模块,因此我可以快速创建用户、以用户身份登录、删除用户和注销用户。这是一个简化的例子:

module UserAuth
    def sign_in(user)
        cookies.permanent[:remember_token] = 'asda'
    end
end

但是,如果我运行此规范:

describe 'UserAuth' do
    include UserAuth

    context 'signed up' do
        let(:user_1) { FactoryGirl.build(:user) }
        before { sign_up user_1 }

        contex 'signed in' do
            before { sign_in user_1 }

            it {}

        end
    end
end

我收到此错误:

   undefined method `permanent' for #<Rack::Test::CookieJar:#>

我觉得奇怪的是 cookies 对象是可用的,但这个 permanent 方法不是出于某种原因。我可以通过简单地在 UserAuth 模块中包含另一个模块来解决此问题吗?如果是这样,这个模块的名称是什么?

【问题讨论】:

    标签: ruby-on-rails cookies rspec


    【解决方案1】:

    似乎 RackTest CookieJar 和 Cookie 类不提供这些方法在其 MockSession 中进行测试。我所做的是以这种方式模拟设置 cookie 的方法,而是返回我自己的结果,或者使用 RackTest 的 cookie 方法来设置 cookie。

    注意:在此示例中,我正在模拟一个通过关注点设置 cookie 的方法。

    before :each do
      allow(MyConcern).to receive(cookie_method) { create(:cookie, :test) }
    end
    
    it 'tests cookie' do
      cookie_method
    
      expect {
        put item_path({test_id: 2})
      }.to change(Item, :test_id)
    
      expect(response.cookies[:cookie_id]).to eq 'test'
    end 
    

    这是另一篇讨论同一问题的 SO 文章,showing implementations

    另一种选择是改用 RackTest 的 CookieJar 方法,它提供了 cookie 创建的基础知识以及其他一些选项。

    it 'has a cookie' do
      cookies[:remember_token] = 'my test'
      post items_path
      expect(response.cookies[:remember_token]).to eq 'my test'
    end
    

    您可以查看 RackTest 的 CookieJar/Cookie Source 中的方法,该方法非常简单,但对于 API docs 则不然。

    我希望这对某人有所帮助,我也希望其他人提出更好的解决方案!

    【讨论】:

      【解决方案2】:

      我建议您按照 Rails 教程中定义的方法进行测试,如http://ruby.railstutorial.org/book/ruby-on-rails-tutorial#code-sign_in_helper 所示。 Rack::Test 中的 CookieJar 对象与 ActionDispatch::Cookies 中 Rails 使用的对象不同。

      查看相关RailsTutorial: NoMethodError 'permanent' Rake::Test::CookieJar

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-07
        • 1970-01-01
        • 1970-01-01
        • 2019-04-25
        • 2021-06-12
        • 1970-01-01
        • 2020-11-27
        • 1970-01-01
        相关资源
        最近更新 更多