Chimed Palden
Chimed Palden

Reputation: 135

Rspec Rails error

let(:valid_attributes) {
    {
      "first_name" => "MyString",
      "last_name" => "LastName",
      "email" => "[email protected]",
      "password" => "password12345",
      "password_confirmation" => "password12345"
    }
  }

it "sets session when" do
        post :create, {:user => valid_attributes}, valid_session
        expect(session[:user_id]).to eq(valid_attributes.id)
end

when i run above test , it fails Failure/Error: expect(session[:user_id]).to eq(valid_attributes["id"])

expected: nil
got: 1

But when i change it to below code , it passes the test. But what is the difference between these two. Why first one is failing.

it "sets session when" do
        post :create, {:user => valid_attributes}, valid_session
        expect(session[:user_id]).to eq(User.find_by(email: valid_attributes["email"]).id)
end

Upvotes: 0

Views: 59

Answers (2)

aliibrahim
aliibrahim

Reputation: 1965

valid_attributes is a simply a hash and it doesn't have anything to do with your User object. Your post will create a User object which will have an id which you are basically trying to check that exists via your test expectations.

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

valid_attributes.id has nothing to do with any Rails magic. You have assigned the value (hash) to valid_attributes in let and compare against it. This value was not changed during test execution, nor was updated from the database. valid_attributes.id was never set ⇒ it is nil.

In the latter case you perform a post action and then check that the value was successfully stored in the database.

Upvotes: 1

Related Questions