Question: Rspec error in session devise with point system

Question

Rspec error in session devise with point system

Answers 1
Added at 2016-12-31 11:12
Tags
Question

I implemented point system. User.point increases by 2 when he does login. My devise session controller is below.

    class Users::SessionsController < Devise::SessionsController
        after_action :add_point, only: [:create]
         # POST /resource/sign_in
         def create
           super
         end
        private

      def add_point
          resource.rewards.create(point: 2)
     end

  end

and My spec/controllers/users_controller_spec.rb is below.

   RSpec.describe UsersController, type: :controller do
   describe 'adds 2 point with login' do
     before do
      @user=create(:user)
      @request.env["devise.mapping"] = Devise.mappings[:user]
    end
    it 'adds 2 point in one day if two times login' do
      expect{post :create, params: {email: @user.email ,password: @user.password} }.to change {@user.points}.by(0)
   end
   it 'adds 4 point in two day ' do
      expect{post :create, params: {email: @user.email ,password: @user.password} }.to change {@user.points}.by(2)
   end
  end 
 end

and my model/user.rb is below.

   class User < ActiveRecord::Base
         def points
          self.rewards.sum(:point)
         end
  end

When I did rspec command , I had this error.

       Failure/Error: expect{login_user(@user)}.to change {@user.points}.by(2)
       expected result to have changed by 2, but was changed by 0

I confirmed that @user.points increased by 2 in view of this application. Why do I have this error? Please tell me.

Answers to

Rspec error in session devise with point system

nr: #1 dodano: 2016-12-31 11:12

You need to reload the user object to track the latest changes

I think this can track the changes of points

post :create, params: {email: @user.email ,password: @user.password}
@user.reload
expect(@user.points).to eql 2
Source Show
◀ Wstecz