I have this spec\requests\sessions_spec.rb
require 'rails_helper'
RSpec.describe "Sessions" do
it "signs user in and out" do
u = sign_in mockuser
p u.inspect
end
end
the above code works well,
but when I call the same sign_in from controller it doesn't, I am fighting this for 10 hours now.
spec\controllers\properties_controller_spec.rb
require 'rails_helper'
describe PropertiesController do
context 'when searching after login' do
it 'should success and render to index page' do
u = sign_in mockuser
p u.inspect // returns nil
end
end
end
my spec\support\devise_request_spec_helper.rb
module DeviseRequestSpecHelpers
include Warden::Test::Helpers
def sign_in(resource_or_scope, resource = nil)
resource ||= resource_or_scope
scope = Devise::Mapping.find_scope!(resource_or_scope)
login_as(resource, scope: scope)
end
end
The Warden test helpers don't work for controller specs since controller specs fake the entire request phase and thus bypass the middleware.
Either use Devise::Test::ControllerHelpers
which stubs out warden or get with the program and ditch controller specs and just write request specs instead.
Request specs provide a high-level alternative to controller specs. In fact, as of RSpec 3.5, both the Rails and RSpec teams discourage directly testing controllers in favor of functional tests like request specs.
- rspec-rails readme
I never had the idea of using request spec in place on controllers. Thanks so much man!
Its a relatively new development / shift that came about around 2015. There are many known problems with controller specs since they stub out huge portions of the framework but we still used them since they were faster than integration tests. The rails team has really put in a lot of work making
ActionDispatch::IntegrationTest
faster though and thats no longer true. The RSpec docs have not caught up though. There should be a big fat warning on the controller specs docs.