RSpec set session object

前端 未结 4 1362
鱼传尺愫
鱼传尺愫 2020-12-15 03:11

I\'m trying to set a session object from my controller spec.

it \'use invalid coupon\' do
  session[:coupon] = \'abcd\'      
  Service.any_instance.stub(:va         


        
相关标签:
4条回答
  • 2020-12-15 03:42

    You can also use @request object like

    @request.session['coupon'] = 'abcd'
    
    0 讨论(0)
  • 2020-12-15 03:49

    This is explained in the Guide to Testing Rails Applications in section 4 "Functional Tests for your Controllers. The get action takes a params hash and a session hash, e.g.:

    get(:show, {'id' => "12"}, {'user_id' => 5})
    

    You should be able to pass in nil for the params hash in your example, then pass in your desired session parameters:

    get :index, nil, {coupon: 'abcd'}
    

    I recommend a thorough reading of the Rails guide for anyone using RSpec for Rails testing. rspec-rails leverages the existing Rails test classes, a point which is not made very clear in the rspec-rails docs.

    0 讨论(0)
  • 2020-12-15 03:56

    In Rails 5+, if you are using ActionController::TestCase session is passed as a keyword arg.

    Setting params and session would look like:

    get(:show, params: {'id' => "12"}, session: {'user_id' => 5})
    

    Setting only the session would look like,

    get(:show, session: {'user_id' => 5})
    

    If you are using ActionDispatch::IntegrationTest, which is the new default for for controller tests, you are not able to set the session variables and should set them by walking your test through the login flow.

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

    You can also do:

    request_params = { city: 'Bomet', code: '023' }
    session_params = { taxes_paid: 'No' }
    

    Then in your spec you can do:

    get :edit, request_params, session_params
    

    In your functionality, you can access your session with session[:taxes_paid]

    0 讨论(0)
提交回复
热议问题