How to import Rails helpers for functional tests

Hi, I recently inherited a project in which a former developer was not familiar with rails, and decided to put a lot of important logic into view helpers.

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

In particular, session management. This works fine with the application, but I am having trouble writing tests for this.

Specific example. Some of the actions are done before_filter to see if current_user administrator. This current_user usually set using the sessions_helper method, which is used in all our controllers. Therefore, in order to test our controllers correctly, I need to be able to use this current_user method

I tried this:

 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 

The require statement finds session_helper.rb in order, but without Rails magic it is not available in the same way as in AppsControllerTest

How can I trick this crazy setup for testing?

+4
source share
4 answers

The only solution I found was to repeat the factor and use a decent auth plugin

+1
source

Why re-factor? You can easily include helpers from your project in your tests. For this, I did the following.

 require_relative '../../app/helpers/import_helper' 
+1
source

If you want to check out helpers, you can follow the example here:

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

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

This is for unit tests by individual methods. I think that if you want to test at a higher level, and you will use several controllers with redirection, you should use the integration test:

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

As an example:

 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 
+1
source

To be able to use Devise in your tests, you must add

 include Devise::TestHelpers 

for each instance of ActionController::TestCase . Then in setup you do

 sign_in users(:one) 

instead

 current_user = users(:one) 

All your functional tests should work fine.

-1
source

All Articles