Creating a controller spec

Hi

I am working through the test fundamentals and I am stuck on getting it to pass.

This is what I have, it seems that the Person is being created 2x.

This is the spec

describe PeopleController do
  describe "#create" do
    context "when person is valid" do
      it "redirects to #show" do
        person = Person.create(first_name: "Scott")
        post :create, person: {first_name: "Scott"}

        expect(response).to redirect_to(person_path(person))
      end
   end
end

This is the output:

Expected response to be a redirect to <http://test.host/people/1> but was a redirect to <http://test.host/people/2>

What have I done wrong?

Thanks

1 Like

The problem is that you’re creating a Person in the database before calling the controller post action. Post.create bypasses your controller and inserts a record directly into the database.

You only need this approach for testing actions which expect an existing record to be present, e.g. edit, update, or show.

3 Likes

Oh how silly of me! Thanks Andy!