質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
RSpec

RSpecはRuby用のBDD(behaviour-driven development)フレームワークです。

Q&A

解決済

1回答

1779閲覧

RSpecでのコメント投稿をテストしたい

退会済みユーザー

退会済みユーザー

総合スコア0

RSpec

RSpecはRuby用のBDD(behaviour-driven development)フレームワークです。

0グッド

0クリップ

投稿2020/06/18 22:57

前提・実現したいこと

RSpecのコメント投稿をテストしたいです。
記事投稿した後でコメント投稿する動作のテストです。

発生している問題・エラーメッセージ

Failure/Error: params.require(:comment).permit(:post_id, :name, :comment, :user_id) NoMethodError: undefined method `permit' for "koment":String

該当のソースコード

rails

1(comments_spec.rb) 2 describe "Comment Success" do 3 let(:user02) { FactoryBot.create(:user02) } 4 it "responds successfully" do 5 post login_path, params: { 6 email: user02.email, 7 password: user02.password, 8 } 9 get posts_index_path 10 expect(response).to have_http_status(:ok) 11 expect { 12 post posts_create_path, params: { 13 content: 'text', 14 user_id: user02.id, 15 } 16 }.to change(Post, :count).by(1) 17 post comments_path, params: { 18 comment: 'koment', 19 user_id: user02.id, 20 } 21 end 22 end 23

rails

1(comments_controller.rb) 2 def create 3 comment = Comment.new(comment_params) 4 comment.user_id = @current_user.id 5 if comment.save 6 flash[:notice] = 'Comment was posted' 7 redirect_to posts_index_path(comment.post_id) 8 else 9 redirect_to posts_index_path(comment.post_id), flash: { 10 comment: comment, 11 error_messages: comment.errors.full_messages 12 } 13 end 14 end 15 16 private 17 18 def comment_params 19 params.require(:comment).permit(:post_id, :name, :comment, :user_id) 20 end

rails

1(routes.rb) 2resources :comments, only: %i[create destroy]

試したこと

解決策がないか検索してこういう記事を見つけて試してみたのですが、attributes_forで解決策は見つかりませんでした。
RSpecでparams.require(:user).permitエラー

すみませんが、アドバイスを頂けると助かります。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

エラーの再現コード

rb

1params = ActionController::Parameters.new(post_id: 1, name: '名前', comment: 'コメント', user_id: 1) 2params.require(:comment).permit(:post_id, :name, :comment, :user_id)

正常な動作をするコード

rb

1params = ActionController::Parameters.new(comment: { post_id: 1, name: '名前', comment: 'コメント', user_id: 1 }) 2params.require(:comment).permit(:post_id, :name, :comment, :user_id)

パラメータの構造に注目してください。
質問者さんの手元で実際に送信されているパラメータの構造はどうなっていますでしょうか。

投稿2020/06/19 00:32

Mugheart

総合スコア2349

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

退会済みユーザー

退会済みユーザー

2020/06/22 16:56

回答ありがとうございます。パラメーターの構造を見て以下に修正したらエラーが出なくなりました。 post comments_path, params: { comment: { comment: 'koment', post_id: post.id, name: 'name', user_id: user02.id, } } ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問