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变量,而对于功能规范来说,它是零.什么是解决方法

编辑:

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

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

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

subject.current_user.email
#or
controller.current_user.email

例如 :

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:

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中:

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...