简体   繁体   English

测试控制器时与rspec指定混合

[英]Mixed up with rspec assigns while testing controller

I'm trying to get a handle on testing controllers, and so far I seem to be stuck on the simplest problems. 我正在尝试了解测试控制器,到目前为止,我似乎仍停留在最简单的问题上。

documents.controller: documents.controller:

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

documents_controller_spec: 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. 始终返回false。 @document is always assigned nil. @document始终分配为nil。 I've tried specifying params[id] to be @doc.id, but that doesn't fix anything. 我尝试将params [id]指定为@ doc.id,但这并不能解决任何问题。 What am I doing wrong here? 我在这里做错了什么?

From rspec's perspective, the two documents (assigned to @doc) you are comparing in the line: 从rspec的角度看,您正在一行中比较两个文档(分配给@doc):

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

are not the same - they have the same ID in the database, but the actual ruby objects you are comparing are different, as one was created in your 'before' block, while the other is presumably instantiated inside your controller when the GET request executes in your test. 是不一样的-它们在数据库中具有相同的ID,但是您要比较的实际红宝石对象是不同的,因为其中一个是在“之前”块中创建的,而另一个可能是在GET请求执行时在控制器内部实例化的在您的测试中。

My guess is the following will work: 我的猜测是以下将起作用:

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

Try changing 尝试改变

get :edit, id: @doc

to

get :edit, id: @doc.id

Basically, it just needs the id to build the route. 基本上,它只需要ID即可构建路线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM