Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use 'reload' method after saving object? (Hartl Rails Tut 6.30)

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) { "[email protected]" }      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 

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.

What am I missing here?

like image 686
sixty4bit Avatar asked Mar 07 '14 20:03

sixty4bit


People also ask

What does reload do Rails?

Reloads the attributes of object(here @user) from the database. It always ensures object has latest data that is currently stored in database.

What does .save do in Ruby?

The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.

Does Rails create save?

create! creates the object and tries to save it but raises an exception if validations fails, e.g. . new and . save!


1 Answers

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.

EDIT: 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

like image 92
Hardik Avatar answered Sep 18 '22 20:09

Hardik