我的 posts_controller_Test.rb 文件:
# test/controllers/posts_controller_test.rb
require 'test_helper'
class PostControllerTest < ActionController::TestCase
def setup
@post = Post.new
end
test 'should get index' do
get :index
assert_response :success
assert_not_nil assigns(:posts)
end
end
我的 post_controller 文件
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
end
为什么我的测试用例
失败了?是因为我有 authenticate_user!
条件吗?我也有 .yml
文件并尝试用它进行测试但是在用 .yml
数据初始化后我得到了 RuntimeError: @controller is nil: make sure you set它在您的测试设置方法中。
yml文件
one:
data 2
value: 3
user_id: 1
name: 'test'
.yml 拥有我在
中需要的一切params.require(:post).permit(:data, :value, :name) and obvious `user` for foreign key reference
编辑-1
建议继承ApplicationController
后
得到这个新错误:
NameError: uninitialized constant ApplicationController::Base
app/controllers/posts_controller.rb:3:in `<top (required)>'
app/controllers/posts_controller.rb:3:in `<top (required)>'
这是我的第 3 行:
class PostsController < ApplicationController::Base
编辑-2
class PostsController < ApplicationController
明白了:
NoMethodError: undefined method `authenticate!' for nil:NilClass
最佳答案
错误是因为您从错误的类继承了 Controller 。改为从 ApplicationController 继承:
class PostsController < ApplicationController
...
end
关于ruby-on-rails - 为什么 rails minitest 测试用例失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31193807/