Ruby初学者です。
現在、ポートフォリオのRspecを書いています。
ご教授頂けますと幸いです。
【困ったこと】
comment_controller_specのテストが通らない。
投稿に対してコメントをつけることができる実装をしました.(SNSのような)
しかしブラウザ上では期待通りの動きをしてくれるのですが、テストが上手くかけなく以下のようなエラーが起こってしまいます。
Failure/Error: post :create, params: { comment: comment_attributes } ActionController::UrlGenerationError: No route matches {:action=>"create", :comment=>{:comment=>"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, :controller=>"comments"}
【コード】
comment_controller_spec.rb
require 'rails_helper' RSpec.describe CommentsController, type: :controller do let!(:user){ create(:user) } let!(:post1){ create(:post, user: user) } let!(:comment){ create(:comment,user_id: user.id,post_id: post1.id) } let!(:comment_attributes){ attributes_for(:comment)} describe "#create" do before do sign_in user end it '投稿を保存する' do expect do post :create, params: { comment: comment_attributes }, session: {} end.to change(Comment, :count).by(1) end end end
routes.rb
resources :posts, only: %i(index show new create destroy) do get "search", on: :collection resources :likes, only: %i(create destroy) resources :comments, only: %i(index create destroy), shallow: true end
comment_controller.rb
def create @comment = Comment.new(comment_params) @post = @comment.post if @comment.save flash[:notice] = "コメントに成功しました" else flash[:alert] = "コメントに失敗しました" end redirect_to post_path(@post) end
ブラウザでは期待通りに動くのでテストの書き方にどこか間違いがあるのでは?と思うのですが、
試行錯誤してみても解決することができずにいます。。。
あなたの回答
tips
プレビュー