簡體   English   中英

如何使用RSpec在Rails中測試ApplicationController的動作之前

[英]How to test before action of ApplicationController in rails using RSpec

我的ApplicationController看起來像這樣

class ApplicationController < ActionController::Base  
  before_action :initialize_fields

  protected

  def initialize_fields
    @company_id_super = nil
    @show_company_super = 0
    @round_id_super = nil
    if(params["controller"] == 'companies')
      if(params["id"].present?)
        @company_id_super = params["id"]
      end
    else
      if(params["company_id"].present?)
        @company_id_super = params["company_id"]
      end
    end
    if(@company_id_super != nil)
      @show_company_super = 1
      @company_super = Company.find(@company_id_super)
    else
      @company_super = nil
    end
    if(params["controller"] == 'home' || params[:controller] == 'votes')
      @hide_side_bar = 1
    else
      @hide_side_bar = 0
    end
    if(params["controller"] == 'rounds')
      if(params["id"].present?)
        @round_id_super = params["id"]
      end
    end
  end
end

我的控制器規格之一看起來像這樣

require 'rails_helper'

RSpec.describe OptionsController, type: :controller do
  describe 'Options controller request specs' do
    login_user
    context 'GET #index' do 
      it 'should success and render to index page' do
        contact = create(:option)
        get :index, params: { company_id: 1 }
        assigns(:options).should eq([option])
      end
    end

    context 'GET #show' do
      let!(:option) { create :option }
      it 'should success and render to edit page' do
        get :show, params: { id: option.id, company_id: 1 }
        expect(response).to render_template :edit
      end
    end
  end
end

現在的問題是,當我運行此規范時,出現以下錯誤:

Failure/Error: @company_super = Company.find(@company_id_super)

ActiveRecord::RecordNotFound:
  Couldn't find Company with 'id'=1
# ./app/controllers/application_controller.rb:36:in `initialize_fields'

現在我知道問題出在應用程序控制器中,但是我不知道如何解決它。 我剛剛開始學習測試,有人可以幫助我嗎? 謝謝 !

發送請求之前,請使用FactoryBot創建Company記錄。

在您的規格/工廠/companies.rb中:

FactoryBot.define do
  factory :company do
    name 'My Company'
    .
    .
  end
end

在您的spec / controllers / options_spec.rb中

RSpec.describe OptionsController, type: :controller do

  let(:my_company) { FactoryBot.create(:company) } 

  describe 'Options controller request specs' do
    login_user
      context 'GET #index' do 
        it 'should success and render to index page' do
           contact = create(:option)
           get :index, params: { company_id: my_company.id } #<--- This will create the company record and pass its ID
           assigns(:options).should eq([option])
        end
      end      
    end
  end
end

因此,現在,在您的initialize_fields ,您將在數據庫中找到公司記錄,並將擺脫錯誤。

暫無
暫無

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

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