如何运行最小的控制器方法? [英] 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
post_controller_test < h1>
post_controller_test
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
参数吗?我做了,但它仍然抛出相同的错误。我也检查了我的路由
文件,因为 post_controller
在开发模式下正常工作。
devise
is setup and working fine but why I am getting 302
error in last two cases. Is it because I am not passing @user
parameters to it? I did but it was still throwing the same error. I also checked out my routes
file which is fine because post_controller
is working fine in development mode.
我在这里做错什么?
我试图创建创建测试用例
方法
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丢失或值为空:post
而在我的控制器类中我确实有
I am getting ActionController::ParameterMissing: param is missing or the value is empty: post
while in my controller class I do have
params.require(:post).permit(:name, :value, :user_id)
我也有我的 .yml
文件中的所有参数,即
I also have all parameters in my .yml
file i.e.
one:
name: 2
value: 3
推荐答案
看起来你需要在尝试之前登录e索引动作。您还在测试错误的实例变量名称。您正在测试@posts,但您已在控制器中定义了@post。尝试这个测试代替:
It looks like you need to sign in before trying the index action. You're also testing the wrong instance variable name. You're testing @posts, but you've defined @post in the controller. Try this test instead:
test 'should get index' do
sign_in @user
get :index
assert_response :success
assert_not_nil assigns(:post)
end
这篇关于如何运行最小的控制器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!