0
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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.