[英]How to run minitest for controller methods?
class PostsController < ActionController::Base
before_action :authenticate_user!
def index
@post = current_user.posts.paginate(page: params[:page], per_page: 5)
respond_to do |format|
format.html
format.json { render json: @post }
end
end
def new
@post = Post.new
end
def create
@post = current_user.posts.build(post_param)
if @post.save
redirect_to action: 'index'
else
render 'new'
end
require 'test_helper'
class PostsControllerTest < ActionController::TestCase
include Devise::TestHelpers
def setup
@user = users(:Bob)
@post = Post.new
end #passed
test 'logged in should get show' do
sign_in @user
get :index
assert_response :success
end #passed
test 'not authenticated should get redirect' do
get :index
assert_response :redirect
end #passed
test 'should get index' do
get :index
assert_response :success
assert_not_nil assigns(:posts)
end #failing
test "should destroy post" do
assert_difference('Post.count', -1) do
delete :destroy, id: @post
end
assert_redirected_to posts_path
end #failing
...
devise
是设置和工作正常,但为什么我在最后两种情况下收到302
错误。 是因为我没有将@user
参数传递给它吗? 我做到了,但它仍然抛出相同的错误。 我还签出了我的routes
文件,这很好,因为post_controller
在开发模式下工作正常。
我在这里做错了什么?
我试图为create
方法创建测试用例
def setup
@user = users(:bob)
@p = posts(:one)
@post = Post.new
end
test 'should create post' do
sign_in @user
assert_difference('Post.count') do
post :create, post: { name: @p.name, value: @p.value}
end
end
我正在获取ActionController::ParameterMissing: param is missing or the value is empty: post
在控制器类中ActionController::ParameterMissing: param is missing or the value is empty: post
时,我确实有
params.require(:post).permit(:name, :value, :user_id)
我的.yml
文件中也有所有参数,即
one:
name: 2
value: 3
看来您需要先尝试登录才能执行索引操作。 您还将测试错误的实例变量名称。 您正在测试@posts,但已在控制器中定义了@post。 请尝试以下测试:
test 'should get index' do
sign_in @user
get :index
assert_response :success
assert_not_nil assigns(:post)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.