在我的 Rails 应用程序中,我有这个更新操作:
class UsersController < ApplicationController
before_filter :authorized_user
def update
current_email = @user.email
new_email = params[:user][:email].downcase.to_s
if @user.update_attributes(params[:user])
if new_email != current_email
@user.change_email(current_email, new_email)
flash[:success] = "Please click on the link that we've sent you."
else
flash[:success] = "User updated."
end
redirect_to edit_user_path(@user)
else
render :edit
end
end
private
def authorized_user
@user = User.find(params[:id])
redirect_to(root_path) unless current_user?(@user)
end
end
class User < ActiveRecord::Base
def change_email(old_email, new_email)
self.email = old_email
self.new_email = new_email.downcase
self.send_email_confirmation_link
end
end
现在,当我在浏览器中手动测试更新操作时,一切正常。
但是,我编写的RSpec测试不起作用,我不知道为什么:
it "changes @user's new_email" do
@user = create(:user, email: "john@doe.com")
put :update, id: @user, user: attributes_for(:user, email: "new@email.com")
@user.reload
expect(@user.new_email).to eq("new@email.com")
end
我不断收到相同的错误消息:
1) UsersController 用户访问 PUT #update 与有效属性更改 @user 的 new_email 失败/错误:expect(@user.new_email).to eq("new@email.com")
expected: "new@email.com"
got: nil
(compared using ==)
谁能告诉我我在这里想念什么?
谢谢你的帮助!