簡體   English   中英

當必須設置方法時,如何測試我的ApplicationController?

[英]How to test my ApplicationController, when a method has to be setup?

我正在使用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方法,該方法返回一個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。

您可以在配置中的: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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM