2016-12-31 37 views
0

我實現了點系統。當他登錄時,User.point增加2。下面是我的設計會議控制器。與點系統的會話設計中的Rspec錯誤

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 

和My spec/controllers/users_controller_spec.rb在下面。

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 

和my model/user.rb在下面。

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

當我做了rspec命令,我有這個錯誤。

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

我確認@ user.points鑑於此應用程序增加了2。爲什麼我有這個錯誤?請告訴我。

回答

1

您需要reload用戶對象跟蹤最新的變化

我覺得這個可以跟蹤點

post :create, params: {email: @user.email ,password: @user.password} 
@user.reload 
expect(@user.points).to eql 2 
+0

哦變化,抱歉試過了,但沒有奏效。 –