我已经创建了一个模块,这样我就可以快速创建用户、作为用户登录、删除用户和注销用户。下面是一个简化的示例:
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模块中包含另一个模块来解决这个问题吗?如果是,这个模块的名称是什么?
发布于 2018-06-11 08:08:06
似乎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 这是另一篇关于同样问题的文章,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来说就没那么多了。
我希望这对某些人有帮助,我也希望其他人能提出更好的解决方案!
发布于 2014-02-02 05:29:59
我建议您遵循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
https://stackoverflow.com/questions/21503397
复制相似问题