4

您好我最近继承了一个项目,其中前开发人员不熟悉rails,并决定将许多重要的逻辑放入视图助手中。如何将Rails助手导入功能测试

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

具体会话管理。这是好的,并与应用程序工作,但我有问题编写测试。

一个具体的例子。某些操作会执行before_filter以查看current_user是否为管理员。这current_user通常是由在我们的所有控制器 共享的sessions_helper方法设定所以,为了正确地测试我们的控制器我需要能够使用此current_user方法

我已经试过这样:

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 

要求声明发现session_helper.rb没问题,但没有Rails的魔法,它不能以相同的方式访问AppsControllerTest

我该如何欺骗这个疯狂的设置来测试?

+2

在AppsControllerTest类中使用'SessionsHelper'并没有帮助?如果您要积极开发此应用程序,我强烈建议您重新编写由他们编写的代码,这没有意义,您将节省时间。这听起来像你只是想让它继续运行,并没有时间去投资。 – Jeremy 2010-11-12 01:07:37

+0

所以看起来像助手正在被包含,因为应用程序控制器在user_helper中调用一个方法,然后在sessions_helper中触发一个错误。所以它好像被包括在内但不能与对方交谈.z – kevzettler 2010-11-12 21:38:58

回答

1

我发现的唯一解决方案是重新考虑因素并使用合适的认证插件

+1

Devise为我工作。 – 2013-05-28 19:08:49

1

为什么要重新考虑?在测试中,您可以非常轻松地包含项目中的助手。我做了以下这样做。

require_relative '../../app/helpers/import_helper' 
-1

为了能够在测试中使用的设计,你应该添加

include Devise::TestHelpers 

每个ActionController::TestCase实例。然后在setup方法你做

sign_in users(:one) 

,而不是

current_user = users(:one) 

您的所有功能测试应该可以正常工作,然后。

+0

原始问题说设计没有被使用。 – kevzettler 2013-11-16 22:27:26

+0

因为常见的'current_user'变量,我假设你在哪里使用Devise。顺便说一句,你从来没有说过你*不*使用Devise。很抱歉对于这个误会。 – marzapower 2013-11-17 11:13:53

1

如果你想测试助手,你可以在这里效仿的榜样:

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