rspec失败,其中'current_user'代码写在控制器中

时间:2014-12-10 16:33:22

标签: ruby-on-rails rspec-rails

我最近开始使用rspec编码,我是rails框架的新手,rspec在我使用的地方失败了' current_user'在控制器中。请在下面查看我的控制器和rspec代码。提前谢谢。

控制器代码:

def task
  @tasks = current_user.alerts.where(kind: "TASK")
end

rspec代码:

describe "get #task" do
  it "assigns a task" do            
    sign_in(@user)
    get :task       
    expect(response).to have_http_status(200)       
  end

1 个答案:

答案 0 :(得分:2)

你可以这样做:

@request.env["devise.mapping"] = Devise.mappings[:user]
 user = FactoryGirl.create(:user) # Don't forget to create a factory for user
 user.confirm! # or set a confirmed_at inside the factory. Only necessary if you are using the "confirmable" module
 sign_in user

最好把它放在support / devise.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

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
  config.extend ControllerMacros, :type => :controller
end

你可以说login_user而不是sign_in(@user)