在rails中测试post动作的问题

时间:2016-03-17 01:52:50

标签: ruby-on-rails ruby

我正在为我的rails应用程序编写测试。我有一个评论模型属于两个不同的模型。代码如下。

class Comment < ActiveRecord::Base

has_ancestry 
  # each comment is created by a user
  belongs_to :user
  # each comment is attached to a scoreboard
  belongs_to :scoreboard

评论控制器如下所示。

def new
 @scoreboard = Scoreboard.find(params[:scoreboard_id])
 @comment = @scoreboard.comments.new  :parent_id => params[:parent_id]
end

def create
 @scoreboard = Scoreboard.find(params[:scoreboard_id])
 @comment = @scoreboard.comments.new comment_params
 respond_to do |format|
  if @comment.save
    format.html { redirect_to scoreboard_url(@comment.scoreboard_id) }
  else
   format.html { 
    redirect_to scoreboard_url(@comment.scoreboard_id)
    flash[:danger] = 'Comment cannot be blank and must be less than 140 characters'
   }
  end
 end
end

评论参数

私有

def comment_params
  params.require(:comment).permit(:body, :parent_id).merge(user_id: current_user.id) #the merge function allows each comment ot be associated with the user
 end

注释夹具文件和integration_test代码如下所示。

comment_a:
   body: myprecious
   user: divjot
   scoreboard: scoreboard_b

class CommentsCreateTest < ActionDispatch::IntegrationTest
  def setup 
    @scoreboard = scoreboards(:scoreboard_b)
    @user = users(:divjot)
    @comment = comments(:comment_a)
  end

  test "successfull creation of the comment" do
xhr :post, scoreboard_comments_path(:id => @scorebaord.id), comment: {body: "abc"}       
end

上面的测试给出了以下错误。

 1) Error:
CommentsCreateTest#test_successfull_creation_of_the_comment:
NoMethodError: undefined method `id' for nil:NilClass
    test/integration/comments_create_test.rb:11:in `block in <class:CommentsCreateTest>'

Scoreboards.yml

scoreboard_a:
  name_of_scoreboard: MyString
  name_of_organization: MyString
  name_of_activity: MyStrings
  states: Ontario
  country: Canada
  cities: Guelph
  created_at: <%= 10.minutes.ago %>
  user: divjot
scoreboard_b:

name_of_scoreboard: MyString
  name_of_organization: MyString
  name_of_activity: MyStrings
  states: Ontario
  country: Canada
  cities: Guelph
  created_at: <%= 10.minutes.ago %>

我不确定为什么会收到此错误。 @scoreboard类在控制器和设置中定义。我想测试将每个评论与记分板和用户相关联的行为。我合并了注释参数中的user_id,以确保每个注释与当前用户相关联。我不确定如何编写反映该行为的测试。我可以传入用户参数,但我不确定。任何有关这方面的帮助将不胜感激!!谢谢!

1 个答案:

答案 0 :(得分:0)

您的测试中似乎有拼写错误。 @scorebaord.id应为@scoreboard.id