3

I'm trying to visit '/requests/new. Now in the controller code, I've written it so that if a session doesn't exist, the user is redirected back to the home page. like so:

def new
@pagetitle = "What would you like to borrow?"

if session[:signup_email].nil?
  flash[:danger] = "Please enter your email to get started"
  redirect_to root_path
else
  @signup_parent = Signup.find_by_email(session[:signup_email].downcase)
  if @signup_parent.tos != true || @signup_parent.streetone.blank? || @signup_parent.streettwo.blank? || @signup_parent.zipcode.blank?
    flash[:danger] = "Almost there! We just need a little more info"
    redirect_to edit_signup_path
  else
    @requestrecord = @signup_parent.requests.build 
  end
end

end

But the problem is that now in testing, I can't simulate a session. I tried to write:

    before do
        session[:signup_email] = Signup.find_by_id(@signup_ana.id)
        visit '/requests/new'
        save_and_open_page
        fill_in '#borrow__1', :with => 1
        click_button
    end

But that threw an error: undefined local variable or methodsession' for #`

Yet if I don't try to simulate it, the save_and_open_page shows me that I just get re-routed back to home. How should I do this? Is there a way to stub/ mock this out??

james
  • 3,989
  • 8
  • 47
  • 102
  • how does the user get a session? That's how you do it - you don't stub or mock it. – sevenseacat Jul 21 '14 at 05:47
  • The user gets a session by putting in his/her email, then the `session[:signup_email]` follows them around. Yes I know I can write tests to mimic this actual behavior, but when I have to write hundreds of them, I'd rather see if there's a way to just say what the session should be instead of visit the page, fill out the email, click the button, etc. – james Jul 21 '14 at 05:51

3 Answers3

1

you can try this gem rack_session_access

Then you can call page.set_rack_session(:user_id => user.id) in Capybara

allenwei
  • 4,047
  • 5
  • 23
  • 26
  • I checked the source, basically it will expose an endpoint which is used to set session, I guess it will work. – allenwei Jul 21 '14 at 04:31
0

For myself I found this two solutions:

  1. https://stackoverflow.com/a/5803121/3797480
  2. https://stackoverflow.com/a/8726895/3797480

The first solution, not to stub authentication process, seems more reasonable in integration(and request) specs as you test the integration of your system components. So I'd not hurt authentication feelings, it is a component too.

Community
  • 1
  • 1
nsave
  • 984
  • 9
  • 27
  • I don't have authentication though, just a session store. In either case, didn't work for me... – james Jul 21 '14 at 17:39
0

you can try this gem rack_session_access Then you can call page.set_rack_session(:user_id => user.id) in Capybara

use allenwei solution and don't forget to add the following require on rails_helper (rails 4+) / spec_helper (rails 3+):

require "rack_session_access/capybara"