控制器中 Post 的 MiniTest

MiniTest for Post in Controller

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

评论table:

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 的方式)。

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