Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

ruby on rails - RSpec set session object

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

it 'use invalid coupon' do
  session[:coupon] = 'abcd'      
  Service.any_instance.stub(:validate_coupon).with(session[:coupon]).and_return('abcd')

  get :index
  expect(flash[:coupon__notice]).to be nil
end

but when I inspect the session, instead of a @coupon object, I get a @data that contains the string 'coupon', and test fails.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...