【问题标题】:How to test my ApplicationController, when a method has to be setup?当必须设置方法时,如何测试我的 ApplicationController?
【发布时间】:2016-01-28 02:26:01
【问题描述】:

我正在使用 rspec,但在尝试测试我的 ApplicationController 时遇到问题。

是否有可能以某种方式设置控制器内部的值?这就是我现在拥有的:

class ApplicationController < ActionController::Base
  include CurrentUser
  before_action :load_account


  private
   def load_user
      @account = current_user.account if current_user.present?
   end
end

包含的模块只是添加了一个返回用户的 current_user 方法。

module CurrentUser
  def self.included(base)
    base.send :helper_method, :current_user
  end

  def current_user
    User.find_by(.....)  # returns a User object
  end
end

所以当我测试我的控制器时,我不需要测试 current_user.rb 的功能,我可以在测试运行之前以某种方式注入 current_user 的值吗?

示例控制器规格:

require 'rails_helper'

RSpec.describe ProductsController, type: :controller do
  it "...." do
    get :new
    expect(response.body).to eq("hello")
  end
end

但目前任何期望 current_user 的控制器都失败了,因为它是 nil。

【问题讨论】:

    标签: ruby-on-rails rspec


    【解决方案1】:

    您可以在 :each 之前在配置中设置一个自定义,它会存根 current_user,这样它就不会破坏您的测试

    RSpec.configure do |config|
      config.before(:each, current_user_present: true) do
        account = double(:account)
        current_user = double(:current_user, account: account)
        expect(controller).to receive(:current_user).and_return(current_user)
        expect(current_user).to receive(:present?).and_return(true)
        expect(current_user).to receive(:account).and_return(account)
      end
    end
    
    RSpec.describe ProductsController, type: :controller, current_user_present: true do
      it "..." do
        #...
      end
    end
    

    【讨论】:

    • current_user 只是一个用户模型,所以我认为我不需要最后 2 个存根。只要我设置用户权限?哦,如果用户为零,那么我需要它们吗?
    猜你喜欢
    • 2022-06-26
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2012-01-22
    • 2013-02-13
    • 1970-01-01
    相关资源
    最近更新 更多