dimitry_n
dimitry_n

Reputation: 3019

Capybara / Poltergeist / Devise @current_user is nil - Rails 4

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:

How can I make sure @current_user works in test?

Upvotes: 2

Views: 856

Answers (2)

dimitry_n
dimitry_n

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

Thomas Walpole
Thomas Walpole

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

Related Questions