Lindsayts
Lindsayts

Reputation: 327

How does @user.save work in user_spec.rb? (rails tutorial chapter 6)

I am doing the Ruby on Rails Tutorial and am up to Listing 6.29. It describes the testing of a (seemingly standard) user authentication process.

My problem is understanding the following (edited) part of the user_spec.rb file:

describe User do

before do
    @user = User.new(name: "Example User", email: "[email protected]", 
                 password: "foobar", password_confirmation: "foobar")
end

subject { @user }

describe "return value of authenticate method" do
    before { @user.save }
    let(:found_user) { User.find_by_email(@user.email) }

    describe "with valid password" do
       it { should == found_user.authenticate(@user.password) }
    end

    describe "with invalid password" do
       let(:user_for_invalid_password) { found_user.authenticate("invalid") }

       it { should_not == user_for_invalid_password }
       specify { user_for_invalid_password.should be_false }
   end
end
end

My main confusion is the line:

before { @user.save }

Does this really save the test user in the database? Won't saving this test user before testing the correctness of its password make the test redundant? It looks to me like I'm merely saving the user (with its password) and then checking if it still has the same password (with which I just saved it!) Is someone able to clarify why I'm mistaken?

Upvotes: 3

Views: 306

Answers (1)

Brad Werth
Brad Werth

Reputation: 17647

Yes, it really does save the user in the database (most likely to be cleaned out by database_cleaner, or something, before the next test - tests are typically meant to be mostly run in isolation from one another and do not usually perpetuate state).

Contrary to making the test redundant, it is a required element. The test in question is for the authenticate method, not user creation. The user is being created in order to test the authenticate method against it. Basically, what is happening here is that it is creating the user, and then trying to authenticate that same user with first a valid password, and next and invalid password, to ensure the proper functionality of the authenticate method.

Upvotes: 1

Related Questions