我實現了點系統。當他登錄時,User.point增加2。 我的設計會議控制器如下。設計會議中的Rspec測試錯誤#create
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
和我的spec/controllers/users_controller_spec.rb位於下面。
RSpec.describe UsersController, type: :controller do
describe 'adds 2 point with login' do
before do
@user=create(:user)
end
it 'adds 2 point in one day if two times login' do
expect{login_user(@user)}.to change {@user.points}.by(0)
end
it 'adds 4 point in two day ' do
expect{login_user(@user)}.to change {@user.points}.by(2)
end
end
end
和我的模型/ 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在rails/console中增加了2。 爲什麼我有這個錯誤?請告訴我。
通過查看答案,我將其更改爲以下。
require 'rails_helper'
RSpec.describe Users::SessionsController, 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(true)}.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(true)}.by(2)
end
end
end
謝謝您發表評論我試過了,但它不工作... –