【问题标题】:Test that associated model has been built?测试关联模型是否已构建?
【发布时间】:2012-01-17 17:06:20
【问题描述】:

我有一个关联模型,我在控制器中为嵌套表单构建该关联

def edit
  @trans_op = TransportOperator.find params[:id]
  @trans_op.coverages.build
end

如何测试@trans_op.coverages.build 行是否存在?

  describe "GET edit" do
    let!(:trans_op){ Factory :trans_op }

    it "should be a success" do
      get :edit, id: trans_op
      response.should be_success
    end

    # this test needs to be fixed
    it "should build an empty coverage if there are none" do
      get :edit, id: trans_op
      # ???
    end
  end

我试过嘲笑:

it "should build an empty coverage if there are none" do
  trans_op.coverages.should_receive(:build)
  get :edit, id: trans_op
end

1) TransportOperatorsController GET edit should add an empty coverage if there are none
   Failure/Error: Unable to find matching line from backtrace
     ([]).build(any args)
         expected: 1 time
         received: 0 times

计数

it "should build an empty coverage if there are none" do
  get :edit, id: trans_op
  trans_op.coverages.count.should == 1
end

失败:

1) TransportOperatorsController GET edit should add an empty coverage if there are none
   Failure/Error: trans_op.coverages.count.should == 1
     expected: 1
          got: 0 (using ==)

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec2


    【解决方案1】:

    您可以通过规范中的assigns 访问控制器变量。因此,例如,这可能会奏效:

    it "should build an empty coverage if there are none" do
      get :edit, id: trans_op
      assigns(:transop).should == trans_op
      assigns(:transop).coverages.should have(1).item
    end
    

    http://rubydoc.info/gems/rspec-rails/2.8.1/file/README.md#assigns

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多