Ruby   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ruby-on-rails – 如何在rspec功能测试中访问(设计)current_user?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
在设计文档中,他们提供了有关在测试控制器时如何访问current_user的提示:

https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-%28and-RSpec%29

但是,在进行功能测试时呢?我试图测试我的一个控制器的创建方法,在该控制器中使用current_user变量.

问题是,devise中建议的宏使用@request变量,而对于功能规范来说,它是零.什么是解决方法?

编辑:

这是我目前为止我目前的规范:

@H_197_12@feature 'As a user I manage the orders of the system' do scenario 'User is logged in ad an admin' do user = create(:user) order = create(:order,user: user) visit orders_path #Expectations end end

问题是在我的ordersController中,我有一个current_user.orders调用,并且由于current_user没有被定义,它将重定向到/ users / sign_in.

我在/spec/features/manage_orders.rb下定义了这个

解决方法

https://github.com/plataformatec/devise/wiki/How-To:-Test-controllers-with-Rails-3-and-4-%28and-RSpec%29

如果我明白你对,也许你需要使用

@H_197_12@subject.current_user.email #or controller.current_user.email

例如 :

@H_197_12@describe ordersController,:type => :controller do login_user describe "POST 'create'" do it "with valid parametres" do post 'create',title: 'example order',email: subject.current_user.email end end end

controller_macros.rb:

@H_197_12@module ControllerMacros def login_user before(:each) do @request.env["devise.mapping"] = Devise.mappings[:user] user = FactoryGirl.create(:user) #user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module sign_in user end end end

不要忘记将其包含在spec_Helper.rb中:

@H_197_12@config.include Devise::TestHelpers,type: :controller config.extend ControllerMacros,type: :controller

大佬总结

以上是大佬教程为你收集整理的ruby-on-rails – 如何在rspec功能测试中访问(设计)current_user?全部内容,希望文章能够帮你解决ruby-on-rails – 如何在rspec功能测试中访问(设计)current_user?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。