← Back to Upcase

Creating a controller spec


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))

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?


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.


Oh how silly of me! Thanks Andy!