代码之家  ›  专栏  ›  技术社区  ›  kevzettler

如何将Rails帮助程序导入到功能测试中

  •  4
  • kevzettler  · 技术社区  · 15 年前

    嗨,我最近继承了一个前开发人员不熟悉Rails的项目,并决定将许多重要的逻辑放入视图帮助器中。

    class ApplicationController < ActionController::Base
      protect_from_forgery
      include SessionsHelper
      include BannersHelper
      include UsersHelper
      include EventsHelper
    end
    

    特别是会话管理。这是可以的,并与应用程序一起工作,但我写这个测试有问题。

    一个具体的例子。有些动作会 before_filter 看看是否 current_user 是管理员。这个 当前用户 通常由 sessions_helper 在所有控制器中共享的方法 所以为了正确测试我们的控制器,我需要能够使用这个 当前用户 方法

    我尝试过:

    require 'test_helper'
    require File.expand_path('../../../app/helpers/sessions_helper.rb', __FILE__)
    
    class AppsControllerTest < ActionController::TestCase
      setup do
        @app = apps(:one)
        current_user = users(:one)
      end
    
      test "should create app" do
        assert_difference('App.count') do
          post :create, :app => @app.attributes
      end
    end
    

    REQUE语句查找 session_helper.rb 好吧,但是如果没有Rails的魔力,就无法以与中相同的方式访问 AppsControllerTest

    我怎么能欺骗这个疯狂的设置来测试?

    4 回复  |  直到 10 年前
        1
  •  1
  •   kevzettler    15 年前

    我找到的唯一解决方案是重新考虑并使用一个合适的身份验证插件。

        2
  •  1
  •   Shawn Deprey    12 年前

    为什么要重新考虑?您可以很容易地将项目中的帮助者包括在测试中。我做了下面的事情。

    require_relative '../../app/helpers/import_helper'
    
        3
  •  1
  •   Chloe    12 年前

    如果要测试助手,可以按照以下示例操作:

    http://guides.rubyonrails.org/testing.html#testing-helpers

    class UserHelperTest < ActionView::TestCase
      include UserHelper       ########### <<<<<<<<<<<<<<<<<<<
    
      test "should return the user name" do
        # ...
      end
    end
    

    这是针对单个方法的单元测试。我认为,如果您希望在更高的级别上进行测试,并且您将使用带有重定向的多个控制器,那么应该使用集成测试:

    http://guides.rubyonrails.org/testing.html#integration-testing

    例如:

    require 'test_helper'
     
    class UserFlowsTest < ActionDispatch::IntegrationTest
      fixtures :users
     
      test "login and browse site" do
        # login via https
        https!
        get "/login"
        assert_response :success
     
        post_via_redirect "/login", username: users(:david).username, password: users(:david).password
        assert_equal '/welcome', path
        assert_equal 'Welcome david!', flash[:notice]
     
        https!(false)
        get "/posts/all"
        assert_response :success
        assert assigns(:products)
      end
    end
    
        4
  •  -1
  •   marzapower Vijay-Apple-Dev.blogspot.com    12 年前

    为了能够在测试中使用design,您应该添加

    include Devise::TestHelpers
    

    给每个人 ActionController::TestCase 实例。然后在 setup 你的方法

    sign_in users(:one)
    

    而不是

    current_user = users(:one)
    

    那么,所有的功能测试都应该可以正常工作。