Unable to set session hash in Rails 5 controller test

后端 未结 4 1490
醉话见心
醉话见心 2020-12-11 03:23

According to the Rails Edge Guide all ActionDispatch::IntegrationTest HTTP requests take optional named keyword arguments:

get post_url, params: { id: 12 }, se

相关标签:
4条回答
  • 2020-12-11 03:43

    I think you can do as this:

    delete cart_url(@cart), params: { 'session' => { :cart_id => @cart.id }}
    
    0 讨论(0)
  • 2020-12-11 03:51

    In Rails 5 it is no longer possible to access session in controller tests: http://blog.napcs.com/2016/07/03/upgrading-rails-5-controller-tests/. The suggestion is to access the controller method that would set the appropriate session value for you. This comment shows and example of how you might work around this limitation: https://github.com/rails/rails/issues/23386#issuecomment-192954569

      # helper method
      def sign_in_as(name)
        post login_url, params: { sig: users(name).perishable_signature )
      end
    
    class SomeControllerTest
      setup { sign_in_as 'david' }
    
      test 'the truth' do
      ..
    
    0 讨论(0)
  • 2020-12-11 03:56

    It turns out that controller tests now inherit from ActionDispatch::IntegrationTest by default and the code that handles the behaviour I wanted sits in ActionController::TestCase.

    So the fix for now is to do the following:

    1 - modify your controller test to inherit from ActionController::TestCase

    class SessionsControllerTest < ActionController::TestCase
    

    2 - modify all of your http request calls to use symbolized action names instead of urls:

    # so change this
    get login_url
    
    # to this
    get :new
    

    And then you should be able to use the new kw_args in your requests like so:

    # now this will work fine
    get :new, session: { user_id: user.id }
    
    # and so will this
    session[:user_id] = user.id
    

    I'm going to open an issue on github later on as I imagine this behaviour is not intended. Thanks to @BoraMa for leading me to the answer

    0 讨论(0)
  • 2020-12-11 04:03

    Try set session through open_session method

    open_session do |sess|
      sess.get "/login", user_id: users(:stephen).id
      assert_redirected_to root_url, 'Expected redirect to root'
    end
    
    0 讨论(0)
提交回复
热议问题