MiniTest for Post in Controller

时间:2016-04-25 18:26:51

标签: ruby-on-rails controller minitest

Comments_controller_test.rb

require 'test_helper'

class CommentsControllerTest < ActionController::TestCase
  test "should create a comment" do

    assert_difference('Comment.count') do
      post :create, comment: {user_id: 1, job_id: 1, content: "This is a comment"}
    end

  end
end

Comments_controller.rb

class CommentsController < ApplicationController

def create
    @comment = Comment.new(comment_params)

    if @comment.save
        render :json => {:status => 'success', :entry => @comment}
    else
        render :json => {:status => 'error'}
    end
end

  def comment_params
    params.require(:comment).permit(:job_id, :user_id, :content)
  end
end

评论表:

class CreateComments < ActiveRecord::Migration
  def change
    create_table :comments do |t|
      t.string :user_id
      t.string :job_id
      t.string :content

      t.timestamps null: false
    end
  end
end

当我跑步时,我得到:

Finished in 0.162164s, 110.9987 runs/s, 117.1653 assertions/s.

1) Failure:
CommentsControllerTest#test_should_create_a_comment       

"Comment.count" didn't change by 1.
Expected: 4
Actual: 3

为什么不创造这个的任何想法?创建注释适用于实际应用程序,但由于某种原因,它没有通过测试

注意:我在灯具中创建了3条评论(这就是它的计数为3)。

1 个答案:

答案 0 :(得分:2)

您可以从服务器调试响应。 在puts response.body之后添加post :create, comment: { ... }并检查日志。