问题描述
我创建了一个模块,以便我可以快速创建用户、以用户身份登录、删除用户和注销用户.这是一个简化的例子:
I've created a module so I can quickly create users, sign in as users, delete users and sign out users. Here is a simplified example:
module UserAuth
def sign_in(user)
cookies.permanent[:remember_token] = 'asda'
end
end
但是,如果我运行此规范:
However, if I run this spec:
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 模块中包含另一个模块来解决这个问题吗?如果是这样,这个模块的名称是什么?
What I find weird about this is that cookies
object is available, but this permanent
method isn't for some reason. Can I resolve this issue by simply including another module in the UserAuth module? If so, what is the name of this module?
推荐答案
RackTest CookieJar 和 Cookie 类似乎没有提供这些方法用于在其 MockSession 中进行测试.我所做的是模拟以这种方式设置 cookie 的方法,而是返回我自己的结果,或者使用 RackTest 的 cookie 方法来设置 cookie.
It seems the RackTest CookieJar and Cookie classes do not offer these methods for testing within its MockSession. What I did is mock the methods setting cookies this way, and rather return my own result, or use RackTest's cookie methods to set cookies.
注意:在这个例子中,我模拟了一个通过关注点设置 cookie 的方法.
Note: In this example I'm mocking a method that is setting a cookie through a concern.
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 文章,并且展示了实现.
Here's another SO article going over this same issue, and showing implementations.
另一种选择是使用 RackTest 的 CookieJar 方法,它提供了 cookie 创建的基础知识,以及其他一些选项.
Another option is to use RackTest's CookieJar methods instead, which offer the basics of cookie creation, as well as few other options.
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 文档.
You can check out the methods in the RackTest's CookieJar/Cookie Source which is very straight-forward, but not so much for the API docs.
我希望对某人有所帮助,我也希望其他人提出更好的解决方案!
I hope that helps someone, and I also hope someone else comes along with a much better solution!
这篇关于尝试创建 cookie 时未定义的方法“永久"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!