繁体   English   中英

如何将Rails助手导入功能测试

[英]How to import Rails helpers in to the functional tests

嗨,我最近继承了一个项目,在该项目中,前开发人员对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

require语句可以找到session_helper.rb但是没有Rails的魔力,就无法以与AppsControllerTest相同的方式进行AppsControllerTest

我该如何欺骗这种疯狂的设置进行测试?

为什么要重构? 您可以轻松地将项目中的帮助程序包括在测试中。 我做了以下操作。

require_relative '../../app/helpers/import_helper'

如果要测试助手,可以在此处遵循示例:

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

我发现的唯一解决方案是重构并使用像样的auth插件

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

include Devise::TestHelpers

到每个ActionController::TestCase实例。 然后在setup方法中

sign_in users(:one)

代替

current_user = users(:one)

这样,您所有的功能测试都应该可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM