How to run minitest for controller methods?

2019-06-01 12:37发布

问题:

post_controller file

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

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 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.

What I am doing wrong here?

Edit-1

I tried to create test cases for create method

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

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)

I also have all parameters in my .yml file i.e.

 one:
  name: 2
  value: 3

回答1:

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