[英]Rails4 Rspec Controller Tests No route matches
所有。 我是Ruby on Rails的初學者。 我一直在努力並且無法解決一個錯誤。
我正在嘗試查看在messages_controller.rb
中聲明的變量@chat_group是否與在message_controller_spec.rb
聲明的另一個變量匹配。 我沒有任何線索可以解決此錯誤,因為我100%肯定我給出了應該給我的參數,就像路由所說的那樣是chat_group_id。
有誰有解決這個問題的見識? 還是以前有人遇到過類似的問題?
如果您已經擁有或擁有,請提供一種解決此問題的方法嗎? 任何意見,將不勝感激! 提前感謝!
1) MessagesController#GET index when the user logs in Checking if the variable in index action matches
Failure/Error: get :index, params: index_params
ActionController::UrlGenerationError:
No route matches {:action=>"index", :controller=>"messages", :params=>{:chat_group_id=>"522"}}
# ./spec/controllers/messages_controller_spec.rb:13:in `block (4 levels) in <top (required)>'
messages_controller_spec.rb
RSpec.describe MessagesController, type: :controller do
let(:chat_group) { create(:chat_group) }
let(:message) { create(:message) }
let(:index_params) { { chat_group_id: chat_group } }
describe '#GET index' do
context 'when the user logs in' do
login_user
it 'Checking if the variable in index action matches' do
get :index, params: index_params
expect(assigns(:chat_group)).to eq chat_group
end
end
end
end
Route.rb
chat_group_messages GET /chat_groups/:chat_group_id/messages(.:format) messages#index
POST /chat_groups/:chat_group_id/messages(.:format) messages#create
chat_groups GET /chat_groups(.:format) chat_groups#index
POST /chat_groups(.:format) chat_groups#create
new_chat_group GET /chat_groups/new(.:format) chat_groups#new
edit_chat_group GET /chat_groups/:id/edit(.:format) chat_groups#edit
chat_group PATCH /chat_groups/:id(.:format) chat_groups#update
PUT /chat_groups/:id(.:format) chat_groups#update
MessageController.rb
class MessagesController < ApplicationController
before_action :set_chat_group
def index
@chat_groups = current_user.chat_groups
@messages = @chat_group.messages
@message = Message.new
respond_to do |format|
format.html { render :index }
format.json { render json:
@chat_group.messages.includes(:user).map{|x| x.json_api} }
end
end
private
def set_chat_group
@chat_group = ChatGroup.find(params[:chat_group_id])
end
end
更新
我解決了錯誤! 我在下面的評論中提出了解決問題的方法!
我很抱歉。 我在看Rails5而不是Rails4的文檔。
它說我應該通過像下面這樣寫來傳遞chat_group_id
。
Rails4
before do
get :index, { chat_group_id: chat_group }
end
不像這樣
before do
get :index, params: { chat_group_id: chat_group }
end
這個錯誤使我意識到閱讀文檔非常重要...對於那些發表評論並嘗試這樣做的人,非常感謝!
嘗試將type: controller
更改type: controller
將type: request
更改為type: request
?
您還可以使用, request type
並指定路徑:
get chat_group_messages_path(chat_group.id), index_params
干杯
我認為您做對了所有事情。
但是這行: expect(assigns(:group)).to eq group
您期望assigns(:group)
但是在您正在測試的索引操作中我看不到任何名為group
變量。
您也希望等於“ eq group
” eq group
,但是在上例中的let
塊中沒有名為group
變量。
所以嘗試做expect(assigns(:chat_groups)).to eq chat_group
assigns(:chat_groups)
在您的操作中使用實例變量的相同名稱,而eq chat_group
在let塊中使用變量的名稱
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.