未定义的方法`评论'为零:NilClass(RSpec)

时间:2016-06-20 23:38:05

标签: ruby-on-rails

目前我正在撰写用于在数据库中设置评论的功能规范。一切似乎都是直截了当的,但我在评论中得到零级错误,我无法弄清楚为什么?我会发布一些代码,看看是否有人可以帮我调试这个问题。

SPEC:

require "rails_helper"

RSpec.feature "Create a Comment" do
 scenario "Customer can leave additional information" do
 visit "/comments/new"

 user = FactoryGirl.create(:user)
 fill_in "Email", with: user.email
 fill_in "Password", with: user.password
 click_button "Sign in"

 fill_in "comment_fav_drink", with: "Latte"
 click_button "Send"

 expect(page).to have_current_path('subscribers/search')
 expect(page).to have_content("Subscriber Has Been Successfully Created")

 end
end

控制器:

 class CommentsController < ApplicationController
 def new
  @comment = Comment.new
 end

  def create
   @subscriber = Subscriber.order('updated_at desc').first
   @comment = @subscriber.comments.build(comments_params)
 if @comment.save
   flash[:notice] = "Thank you!"
   redirect_to subscribers_search_path(:comments)
  else
   render "new"
  end
end

private

def comments_params
  params.require(:comment).permit(:fav_drink, :subscriber_id)
end

1 个答案:

答案 0 :(得分:1)

comments行动中唯一调用@subscriber.comments方法的地方为create,这意味着@subscribernil,回顾过去你把它设置为Subscriber.order('updated_at desc').first这意味着返回nil这意味着你的数据库在你的测试运行时没有订户,这与我的测试结果相符(即你是没有创建任何订阅者)