Mixes with rspec assignment when testing a controller

I am trying to get instructions for testing controllers, and so far I seem to be sticking to the simplest problems.

documents.controller:

def edit @document = Document.find(params[:id]) end 

documents_controller_spec:

  describe 'GET #edit', focus: true do before(:each) { @doc = FactoryGirl.create(:document)} it "should assign @document to the document" do get :edit, id: @doc assigns(:document).should eq(@doc) end end 

Always returns false. @document is always assigned nil. I tried to specify params [id] as @ doc.id, but that didnโ€™t fix anything. What am I doing wrong here?

+4
source share
2 answers

From the rspec point of view, there are two documents (assigned to @doc) that you are comparing in a line:

 assigns(:document).should eq(@doc) 

don't match - they have the same identifier in the database, but the actual ruby โ€‹โ€‹objects you are comparing are different, because one was created in your before block and the other is supposedly created inside your controller when the GET request is executed in your test.

My guess is this:

 assigns(:document).id.should eq(@doc.id) 
+5
source

Try to change

 get :edit, id: @doc 

to

 get :edit, id: @doc.id 

In principle, to build a route, you just need an identifier.

+1
source

All Articles