![](/img/trans.png)
[英]Minitest - test ApplicationController before_action in Rails 4
[英]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.