Reputation: 3019
I got a feature spec which receives a token from an external site and redirects back to my app. Upon redirecting, the client is served an orders#new
view, which calls @current_user.items
. This call works in all environments except test. Capybara / Poltergeist or Selenium get undefined method items for nil class
I've tried:
@current_user
in before(:each)
@current_user
to User.first
for Rails.env.test?
in my
controllerHow can I make sure @current_user
works in test?
Upvotes: 2
Views: 856
Reputation: 3019
Tom's answer made me realize that cookies are not stored because Capybara hosts are not static. I ended up explicitly setting the server_port
, server_host
and app_host
in the rails_helper
which worked like a charm:
Capybara.app_host = 'http://localhost:3000'
Capybara.server_host = 'localhost'
Capybara.server_port = '3000'
My app is not using Devise and Warden. Otherwise, Tom's answer would've worked.
Upvotes: 0
Reputation: 49950
You need to either login in your feature spec, or use wardens test mode through devise to fake the login - see https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara - so that the current user is set (along with the relevant session cookies). Feature tests and the app each run separately when using any Capybara driver other than rack-test so attempting to set @current_user in a before(:each) isn't going to work. Setting it in the controller would probably work for that controller action but won't set the session cookies if you're following links, etc - and doing something like that in a controller just for testing is generally a bad idea.
Upvotes: 1