4
votes

The listing 6.20 of Michael Hartl's rails tutorial shows the following code:

before do
    @user = User.new(name: "Example User", email: "[email protected]")
  end
  .
  .
  .
  describe "when email address is already taken" do
    before do
      user_with_same_email = @user.dup
      user_with_same_email.email = @user.email.upcase
      user_with_same_email.save
    end

    it { should_not be_valid }
  end

I am having trouble grasping this concept because @user.dup returns a representation of the exact same object, which is copied over to user_with_same email, but @user was never saved into the database anywhere in the file. Therefore, the user_with_same_email.save test should be valid every time. However, the test passes. Someone please explain this... is there an implicit database save on @user = User.new(...)? I know if it was User.create(...) there would be a save, but not for the new method. Thanks!

1

1 Answers

4
votes

You're not missing an implicit save.

user_with_same_email does save correctly (personally I would always use save! to be sure it was not failing silently)

What the spec is speccing is that the subject (ie @user) cannot be saved, because of the existance of a row in the database with the same email.