1
votes
  • rails (5.1.4)
  • rspec-rails (3.7.2)
  • capybara (2.16.1)
  • devise (4.3.0)

I'm trying to create a RSpec Rails 3.7 System spec as in https://relishapp.com/rspec/rspec-rails/v/3-7/docs/system-specs/system-spec .

Additionally I want to apply the Devise authorization. I followed the instruction https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara

But I guess it's kind of a defective implementation. I don't get the current_user method (which is nil).

Here my simple spec:

require 'rails_helper'

RSpec.describe "testing system", type: :system do

  it "tests the spec" do

    admin = create(:admin) # user-admin

    login_as(admin, :scope => :admin)

    visit root_path

    click_link 'Home'

    save_and_open_page

  end
end

Since the code on my site depends heavily on the current_user value, I don't get a properly formed saved page (it looks like a user did not log in).

What should I do? Should I try to simply manually (somehow?) assign a value to current_user? Or maybe the https://github.com/plataformatec/devise/wiki/How-To:-Test-with-Capybara strategy is mainly defective and should be substituted to something more full-fledged technology?

I already tried to make

current_user = admin

in my code - but with no result.

1

1 Answers

3
votes

The devise wiki is correct for how to test while shortcutting logins, and no you can't just set current_user in your test code (nor can you access it since it's only set inside the request). Generally assume the error is in your usage of a gem, rather than a widely used and highly tested gem being defective.

With the description you've given there could be any number of reasons for it not actually logging in the user however the two most likely culprits are

  1. Do you actually have multiple scopes configured in Devise? or should it just be login_as(admin, :scope => :user) # equivalent to just login_as(admin)

  2. Is puma running your tests in single mode, or clustered mode? (You may need to disable the silencing of puma output rspec-rails does by default -https://github.com/rspec/rspec-rails/blob/95f4522c0549a32de59c19eb9b5f9a72126a9eb6/lib/rspec/rails/example/system_example_group.rb#L72 - to see that in the test output) If it's not in single mode then the app is being run in a separate process than the tests which means Devise can't actually shortcircuit the login, and you need to fix the puma config.