RSpec 设置会话对象 [英] RSpec set session object

查看:54
本文介绍了RSpec 设置会话对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据我的控制器规范设置会话对象.

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

但是当我检查会话时,我得到的不是@coupon 对象,而是包含字符串coupon"的@data,并且测试失败.

but when I inspect the session, instead of a @coupon object, I get a @data that contains the string 'coupon', and test fails.

推荐答案

这在 Guide to Testing 中有解释Rails 应用程序在第 4 节控制器的功能测试.get 操作需要一个参数哈希一个会话哈希,例如:

This is explained in the Guide to Testing Rails Applications in section 4 "Functional Tests for your Controllers. The get action takes a params hash and a session hash, e.g.:

get(:show, {'id' => "12"}, {'user_id' => 5})

您应该能够为示例中的 params 哈希传入 nil,然后传入所需的会话参数:

You should be able to pass in nil for the params hash in your example, then pass in your desired session parameters:

get :index, nil, {coupon: 'abcd'}

我建议任何使用 RSpec 进行 Rails 测试的人都仔细阅读 Rails 指南.rspec-rails 利用了现有的 Rails 测试类,这一点在 rspec-rails 文档中没有说得很清楚.

I recommend a thorough reading of the Rails guide for anyone using RSpec for Rails testing. rspec-rails leverages the existing Rails test classes, a point which is not made very clear in the rspec-rails docs.

这篇关于RSpec 设置会话对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆