wolf
wolf

Reputation: 419

undefined method 'person' for nil:NilClass

I am trying to create contact manager by following a tutorial. I think that tutorial missing some part and I am stuck while writing tests.

describe "POST #create" do
context "with valid params" do
  it "creates a new PhoneNumber" do
    expect {
      post :create, params: {phone_number: valid_attributes}, session: valid_session
    }.to change(PhoneNumber, :count).by(1)
  end

  it "redirects to the phone number's person" do
    alice = Person.create(first_name: 'Alice', last_name: 'Smith')
    valid_attributes = {number: '555-8888', person_id: alice.id}
    post :create, params: {:phone_number => valid_attributes}, session: valid_session
    expect(response).to redirect_to(@phone_number.person)
  end
 end
end

My code gives the following error

   undefined method `person' for nil: NilClass

As far as I understand, somehow I need to initialize @phone_number. Since I am new to rails I could not figure it out.

Any help would be nice.

Upvotes: 0

Views: 114

Answers (2)

Dorian
Dorian

Reputation: 23949

You can just do:

expect(response).to redirect_to(alice)

Upvotes: 1

Raj
Raj

Reputation: 22926

Maybe try finding based on the attributes used to create the phone number:

@phone_number = PhoneNumber.find_by(number: '555-8888')
expect(response).to redirect_to(@phone_number.person)

Upvotes: 1

Related Questions