Ruby初学者です。
現在、Rspecを学んでいます。
ご教授頂けますと幸いです。
【実現させたいこと】
・createアクションのテストを通したい。
【エラー内容】
以下のように、コントローラー内のpostsがnilと現れます。
しかし、ブラウザ上では問題なく動いています。
Failure/Error: @post = current_user.posts.build(post_params) NoMethodError: undefined method `posts' for nil:NilClass
【コード】
posts_controller.rb
def create @post = current_user.posts.build(post_params) if @post.save flash[:notice] = "投稿が保存されました" redirect_to posts_path else redirect_to posts_path flash[:alert] = "投稿に失敗しました" end end
spec/posts_controller.spec.rb
describe "#create" do context "登録していないユーザー" do it "302レスポンスを返す" do post_params = FactoryBot.attributes_for(:post) post :create, params: { post: post_params } expect(response).to have_http_status 302 end
【参考】
コントローラーのcreateアクションの実装は、rails tutorialの以下の実装を参考にしました。
def create @micropost = current_user.microposts.build(micropost_params) if @micropost.save flash[:success] = "Micropost created!" redirect_to root_url else @feed_items = [] render 'static_pages/home' end end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。