保存对象后为什么要使用“重新加载"方法? (Hartl Rails Tut 6.30) [英] Why use 'reload' method after saving object? (Hartl Rails Tut 6.30)

查看:53
本文介绍了保存对象后为什么要使用“重新加载"方法? (Hartl Rails Tut 6.30)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究《 Hartl的Rails 4教程》第6章的练习.第一次练习测试是为了确保用户电子邮件地址的大小写正确无误:

I'm working on the exercises for chapter 6 of Hartl's Rails 4 Tutorial. The first exercise tests to make sure that user email addresses are down-cased correctly:

require 'spec_helper'

describe User do
  .
  .
  .
  describe "email address with mixed case" do
    let(:mixed_case_email) { "Foo@ExAMPle.CoM" }

    it "should be saved as all lower-case" do
      @user.email = mixed_case_email
      @user.save
      expect(@user.reload.email).to eq mixed_case_email.downcase
    end
  end
  .
  .
  .
end

我不明白的是为什么在这里需要'reload'方法.将@user.email设置为mixed_case_email保存的内容后,@user.reload.email@user.email是不是一回事?我只是尝试尝试了reload方法,但是测试似乎并没有改变任何东西.

What I don't understand is why the 'reload' method is necessary here. Once @user.email is set to the contents of mixed_case_email and saved, aren't @user.reload.email and @user.email the same thing? I took the reload method out just to try it and it didn't seem to change anything with the test.

我在这里想念什么?

推荐答案

在这种情况下,@user.reload.email@user.email是同一回事.但是,使用@user.reload.email而不是@user.email来检查数据库中到底保存了什么是一个好习惯,我的意思是您不知道自己是否有人在after_save中添加了一些代码,这些代码会更改其值,因此对您的测试.

Yes in this case @user.reload.email and @user.email is the same thing. But it's good practice to use @user.reload.email instead of @user.email to check what is exactly saved in the database i mean you don't know if you or someone add some code in after_save which changes it's value then it will not have effect on your tests.

另外,您要检查的是数据库中保存的内容,因此@user.reload.email准确地反映了数据库中保存的内容,然后@user.email

And also what you are checking is what's saved in the database so @user.reload.email exactly reflects what's saved in database then @user.email

这篇关于保存对象后为什么要使用“重新加载"方法? (Hartl Rails Tut 6.30)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆