如何将Rails助手导入function测试
嗨,我最近inheritance了一个项目,其中前开发人员不熟悉rails,并决定在视图助手中加入许多重要的逻辑。
class ApplicationController < ActionController::Base protect_from_forgery include SessionsHelper include BannersHelper include UsersHelper include EventsHelper end
特别是会话管理。 这是可以的,并与应用程序一起工作,但我在为此编写测试时遇到问题。
一个具体的例子。 某些操作执行before_filter
以查看current_user
是否为admin。 这个current_user
通常由我们所有控制器共享的sessions_helper
方法设置所以为了正确测试我们的控制器,我需要能够使用这个current_user
方法
我试过这个:
require 'test_helper' require File.expand_path('../../../app/helpers/sessions_helper.rb', __FILE__) class AppsControllerTest @app.attributes end end
require语句发现session_helper.rb
没问题,但没有Rails魔法,它在AppsControllerTest
无法以相同的方式AppsControllerTest
我怎么能欺骗这个疯狂的设置进行测试?
我找到的唯一解决方案是重新考虑并使用一个像样的auth插件
为什么重新考虑? 您可以非常轻松地在测试中包含项目中的帮助程序。 我做了以下这样做。
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
这是针对单个方法的unit testing。 我认为如果你想在更高级别进行测试,并且你将使用多个控制器w /重定向,你应该使用集成测试:
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
为了能够在测试中使用Devise,您应该添加
include Devise::TestHelpers
到每个ActionController::TestCase
实例。 然后在你setup
方法中
sign_in users(:one)
代替
current_user = users(:one)
那么你所有的function测试都应该可以正常工作。