【问题标题】:Why rails minitest testcases are failing为什么 Rails minitest 测试用例失败
【发布时间】:2015-07-02 20:11:19
【问题描述】:

我的 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

为什么我的test cases 失败了?是因为我有authenticate_user! 条件吗?我也有.yml 文件并尝试使用它进行测试,但在使用.yml 数据初始化后我得到RuntimeError: @controller is nil: make sure you set it in your test's setup method.

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 minitest


    【解决方案1】:

    错误是因为您从错误的类继承了控制器。改为从 ApplicationController 继承:

    class PostsController < ApplicationController
      ...
    end
    

    【讨论】:

    • 感谢您的回答。你能看看Edit-2部分
    • 现在你问了一个完全不同的问题。如果这解决了您最初的问题,请将此答案标记为已接受并打开一个新问题。
    • 感谢您的帮助!我弄清楚了为什么它不起作用以及如何在测试用例中包含devise 用户会话。但是这次我遇到了稍微不同的问题。这是我的问题:stackoverflow.com/questions/31194778/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多