0

I'm new to testing and tried to test a simple get-Request to this Controller-Method:

def new
  u = User.new({firstname: 'John',lastname: 'Smith'})
  u.save
end

When i request this method through the browser a new User gets created.

Now i tried to test this get request:

require 'spec_helper'
describe UsersController, :type => :controller do 

    describe 'GET #new' do 

        it "generates a fake User" do 
            expect {get :new}.to change(User, :count).by(1)
        end

    end
end

But somehow this test fails i get the message:

   expected #count to have changed by 1, but was changed by 0

What do i wrong? Thanks

John Smith
  • 6,105
  • 16
  • 58
  • 109
  • GET is supposed to be idempotent -- in other words, you can issue the same get X times without any side effects. You are not following that "guideline/stricture/rule/whatever". Your GET shouldn't be a GET if you are altering state on the backend. POST is probably your best option, since POST is fairly ambiguous on just what is allowed as the result of a POST request. – railsdog Jan 12 '15 at 02:33

1 Answers1

0

John, sending a POST request to #new rather than a GET should clear up that problem. This stack overflow question should help with discerning when to use POST vs GET When should I use GET or POST method? What's the difference between them?

As an aside, the convention is to use POST#create to instantiate something and save it to the database in the same function. That way the GET#new renders the new.html.erb view and the 'submit' button on that form actually sends the POST#create with the params that have been entered.

Community
  • 1
  • 1
bholcomb
  • 16
  • 1