Ruby-on-rails RSpec 设置会话对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22451969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RSpec set session object
提问by parov
I'm trying to set a session object from my controller spec.
我正在尝试从我的控制器规范中设置一个会话对象。
it 'use invalid coupon' do
session[:coupon] = 'abcd'
Service.any_instance.stub(:validate_coupon).with(session[:coupon]).and_return('abcd')
get :index
expect(flash[:coupon__notice]).to be nil
end
but when I inspect the session, instead of a @coupon object, I get a @data that contains the string 'coupon', and test fails.
但是当我检查会话时,而不是@coupon 对象,我得到一个包含字符串“coupon”的@data,并且测试失败。
回答by zetetic
This is explained in the Guide to Testing Rails Applicationsin section 4 "Functional Tests for your Controllers. The getaction takes a params hash anda session hash, e.g.:
这在“测试 Rails 应用程序指南”的第 4 节“控制器的功能测试”中进行了解释。该get操作需要一个 params 哈希和一个会话哈希,例如:
get(:show, {'id' => "12"}, {'user_id' => 5})
You should be able to pass in nilfor the params hash in your example, then pass in your desired session parameters:
您应该能够nil在示例中传入 params 哈希,然后传入所需的会话参数:
get :index, nil, {coupon: 'abcd'}
I recommend a thorough reading of the Rails guide for anyone using RSpec for Rails testing. rspec-railsleverages the existing Rails test classes, a point which is not made very clear in the rspec-railsdocs.
对于使用 RSpec 进行 Rails 测试的任何人,我建议彻底阅读 Rails 指南。rspec-rails利用现有的 Rails 测试类,这一点在rspec-rails文档中不是很清楚。
回答by HParker
In Rails 5+, if you are using ActionController::TestCasesession is passed as a keyword arg.
在 Rails 5+ 中,如果您使用的ActionController::TestCase是 session,则作为关键字 arg 传递。
Setting params and session would look like:
设置参数和会话看起来像:
get(:show, params: {'id' => "12"}, session: {'user_id' => 5})
Setting only the session would look like,
仅设置会话看起来像,
get(:show, session: {'user_id' => 5})
If you are using ActionDispatch::IntegrationTest, which is the new default for for controller tests, you are notable to set the session variables and should set them by walking your test through the login flow.
如果您使用的ActionDispatch::IntegrationTest是控制器测试的新默认值,则您无法设置会话变量,而应通过在登录流程中执行测试来设置它们。
回答by Vignesh Jayavel
You can also use @request object like
您还可以使用@request 对象,如
@request.session['coupon'] = 'abcd'
回答by Ruto Collins
You can also do:
你也可以这样做:
request_params = { city: 'Bomet', code: '023' }
session_params = { taxes_paid: 'No' }
Then in your spec you can do:
然后在您的规范中,您可以执行以下操作:
get :edit, request_params, session_params
In your functionality, you can access your session with session[:taxes_paid]
在您的功能中,您可以访问您的会话 session[:taxes_paid]

