ruby-on-rails - rspec 失败, Controller 中写入的代码为 'current_user'

标签 ruby-on-rails rspec-rails

我最近开始了 rspec 编码,而且我是 Rails 框架的新手,当我在 Controller 中使用“current_user”时,rspec 失败了。请检查下面我的 Controller 和 rspec 代码。提前致谢。

Controller 代码:

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

最佳答案

你可以这样做:

@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)

关于ruby-on-rails - rspec 失败, Controller 中写入的代码为 'current_user',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27406153/

相关文章:

ruby-on-rails - Rails 4 - pundit - 如何编写 if 语句来检查用户权限

ruby-on-rails - RSpec:Let 语句有时会出现问题,因为当我执行 get 请求时,我需要它们的值存在于数据库中

rspec - 如果发生超时::错误,则自动重新运行 rspec 示例

ruby-on-rails-3 - 未定义的局部变量或方法 `render'

rspec-rails - 运行 rspec 时拾取 Rufus 调度程序任务

ruby-on-rails - Rspec 请求规范期间 Rails 4 中的循环依赖错误

ruby-on-rails - rake/rails 。保存!不更新数据库

ruby-on-rails - rails : test mailgun on localhost

ruby-on-rails - 为什么我的模型的唯一性验证规范在应该通过时却失败了?

ruby-on-rails - 未初始化的常量 ReviewsController::Reviews