从 rspec 中的帮助程序规范访问会话 [英] Accessing session from a helper spec in rspec
问题描述
我的 ApplicationHelper 中有一个方法可以检查我的篮子里是否有任何物品
I have a method in my ApplicationHelper that checks to see if there are any items in my basket
module ApplicationHelper
def has_basket_items?
basket = Basket.find(session[:basket_id])
basket ? !basket.basket_items.empty? : false
end
end
这是我必须测试的辅助规范:
Here is my helper spec that I have to test this:
require 'spec_helper'
describe ApplicationHelper do
describe 'has_basket_items?' do
describe 'with no basket' do
it "should return false" do
helper.has_basket_items?.should be_false
end
end
end
end
但是当我运行测试时我得到
however when I run the test i get
SystemStackError: stack level too deep
/home/user/.rvm/gems/ruby-1.9.3-p194/gems/actionpack-3.2.8/lib/action_dispatch/testing/test_process.rb:13:
从调试中我看到 session 正在 ActionDispatch::TestProcess 中从 @request.session 访问,而 @request 为零.当我从我的请求规范访问会话时,@request 是 ActionController::TestRequest 的一个实例.
From debugging this i see that session is being accessed in ActionDispatch::TestProcess from @request.session, and @request is nil. When i access the session from my request specs @request is an instance of ActionController::TestRequest.
我的问题是我可以从辅助规范访问会话对象吗?如果可以,怎么做?如果我不能测试这种方法的最佳实践是什么?
My question is can I access the session object from a helper spec? If I can, how? And if I cant what is the best practice to test this method?
****更新****
****UPDATE****
这归结为在我的工厂中有 include ActionDispatch::TestProcess
.删除此包含可对问题进行排序.
This was down to having include ActionDispatch::TestProcess
in my factories. Removing this include sorts the problem.
推荐答案
我可以从辅助规范访问会话对象吗?
是的.
module ApplicationHelper
def has_basket_items?
raise session.inspect
basket = Basket.find(session[:basket_id])
basket ? !basket.basket_items.empty? : false
end
end
$ rspec spec/helpers/application_helper.rb
Failure/Error: helper.has_basket_items?.should be_false
RuntimeError:
{}
会话对象在那里并返回一个空的哈希值.
The session object is there and returns an empty hash.
尝试更详细地查看回溯以找出错误.stack level too deep
通常表示递归出错了.
Try reviewing the backtrace in more detail to find the error. stack level too deep
usually indicates recursion gone awry.
这篇关于从 rspec 中的帮助程序规范访问会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!