简体   繁体   中英

How can I get Minitest to resolve helper in a controller test?

I have a failing controller test that is just testing that an index route returns a 200 response.

The controller in question has before_action:is_authenticated? , where is_authenticated? is defined in a helper auth_helper.rb included in ActionController (since my intention is to use it across multiple controllers).

When I interact with my app, the is_authenticated? method is executed normally. When I run my test suite, I get the following error message:

# Running:

....E

Error:
EventsControllerTest#test_should_fail_creation_with_invalid_data:
NoMethodError: undefined method `is_authenticated?' for #<Api::V1::EventsController:0x00007f943966c2c0>
    test/controllers/events_controller_test.rb:19:in `block in <class:EventsControllerTest>'

rails test test/controllers/events_controller_test.rb:18

Here is my test:

require 'test_helper'

class EventsControllerTest < ActionDispatch::IntegrationTest
  setup do
    @event = Event.first
    
    register
  end
  
  test "should get index" do
    get "/api/v1/events"
    assert_response :success

    events = JSON.parse(response.body)
    assert_equal(events.length, 2)
  end
end

Here is the code in auth_helper.rb :

module AuthHelper
    def is_authenticated?
        if is_user_signed_in?
            return true
        else
            render json: { error: "You must be logged in" }, status: :unauthorized 
        end
    end
end

How can I get my test to properly simulate the request, using the helper, just as a live request would?

I've tried requiring the helper in the test and defining it in the setup code instead, but that doesn't seem to help.

I'm new to Rails so any feedback would be greatly appreciated. Thanks!

I ended up solving the problem I was having by putting the code inside of a Concern instead of a helper module.

By including the code in a concern, and then adding the concern to ApplicationController , the is_authenticated? function is picked up by my code, and is resolved during the test suite execution.

It's still not clear to me what the difference is between how regular modules and rails concerns get resolved, but adding a concern has achieved the desired behaviour in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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