Search code examples
ruby-on-railsrubyrspecrspec-rails

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

Solution

  • 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.