0

In the following example the @user.expects(:send_invitations!).once assertion is failing, even though the invitations are being sent by the app and the @send_invitations variable is being assigned. Would you expect @user.send_invitations! to be invoked at this point or is @user.expects(:send_invitations!) being used incorrectly?

The Controller

class RegistrationsController < ApplicationController
  before_filter :require_active_user

  def welcome
    if params[:send_invitations]
      current_user.send_invitations!
      @send_invitations = true
    end
  end   
end           

The Controller Test

require 'test_helper'

class RegistrationsControllerTest < ActionController::TestCase
  context "With a logged-in user" do
    setup { login_as @user = Factory(:user) }

    context ":welcome" do
      context "with params[:send_invitations] present" do
        setup { get :welcome, { :send_invitations => true } }

        should "send invitations" do
          @user.expects(:send_invitations!).once # tests say this isn't being invoked
          assert assigns(:send_invitations) # but tests say this IS being assigned
        end
      end

      context "without the presence of params[:send_invitations]" do
        setup { get :welcome }

        should "not send invitations" do
          @user.expects(:send_invitations!).never # passes fine
          assert !assigns(:send_invitations!) # also passes fine          
        end
      end
    end
  end
end
Neil
  • 189
  • 1
  • 1
  • 9
  • you should stub the current_user method to make it return @user – apneadiving May 15 '12 at 21:26
  • What does your login_as method look like? It appears that @user and current_user are not the same instance of a User. – Tom L May 15 '12 at 21:53
  • @apneadiving, Tom L funnily enough User.any_instance.expects(:send_invitations!).once doesn't pass either. Would you expect current_user to be included in that? – Neil May 16 '12 at 07:36
  • Sorry for the late follow up. I never got a update notice. I'd expect current_user to be included but that may depend on what the login_as method is doing. Is it just stubbing some method such that current_user is never set? – Tom L May 21 '12 at 00:43
  • @TomL it does `class ActionController::TestCase def login_as(user) user = user.is_a?(Symbol) ? Factory(user) : user @request.session[:user_id] = user.id user end end`, so it's getting a user from the Factory which sounds like it should be including it in the User.any_instance.expects... – Neil May 21 '12 at 06:02
  • Are you using Devise for authentication? Take a look at this: http://stackoverflow.com/questions/8705790/how-to-stub-out-warden-devise-with-rspec-in-capybara-test – Tom L May 21 '12 at 17:43
  • @TomL Thanks for the link - it's AuthLogic but only using Oauth. – Neil May 22 '12 at 06:35
  • I haven't used Authlogic myself but look into stubbing the UserSession class or the set_session_for helper method. – Tom L May 22 '12 at 14:40

0 Answers0