Search code examples
rspecdeviseuser-registration

Rspec test Devise RegistrationsController with AbstractController error


Rspec config

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
...

Routes

devise_for :users, controllers: { passwords: "users/passwords", sessions: "users/sessions", registrations: "users/registrations"}

About SessionsController

class Users::SessionsController < Devise::SessionsController    
end

Test code

require 'spec_helper'

describe Users::SessionsController do

controller do
  def after_sign_in_path_for(resource)
    super resource
  end
end

describe "After user sigin-in" do
  before(:each) do
    @user = FactoryGirl.create(:user)     
  end

  it "change current_user" do
    sign_in @user
    expect( subject.current_user ).to eq(@user)
  end

  it "redirects to the user_root_path" do
    user = FactoryGirl.create(:user)
    controller.after_sign_in_path_for(@user).should == root_path
  end
end
...

This test passes successfully! But when I do RegistrationsController test the same way, I got an error:

Test code

require 'spec_helper'

describe Users::RegistrationsController do

controller do
  def after_sign_up_path_for(resource)
    super resource
  end
end

describe "User sign_up" do  

it "change current_user" do
  post :create, user: FactoryGirl.attributes_for(:register_user)
  expect( subject.current_user ).not_to be nil
end
...

Error

Users::RegistrationsController User sign_up change current_user
 Failure/Error: post :create, user: FactoryGirl.attributes_for(:register_user)
 AbstractController::ActionNotFound:
   The action 'create' could not be found for AnonymousController
 # ./spec/controllers/registrations_controller_spec.rb:18:in `block (3 levels) in <top (required)>'

Solution

  • I made some mistakes to user method controller in *_spec.rb file, it defines an anonymous controller which inherit from the described class. You can also change it inheriting from ApplicationController by change the config in spec_helper.rb

    config.infer_base_class_for_anonymous_controllers = false
    

    You can reference the link for more https://www.relishapp.com/rspec/rspec-rails/docs/controller-specs/anonymous-controller