【问题标题】:Rspec for building nested attributes用于构建嵌套属性的 Rspec
【发布时间】:2015-12-22 19:03:05
【问题描述】:

我的CompaniesController中有以下代码sn-p

class CompaniesController < ApplicationController
  def new
    @company  = Company.new
    @company.employees.build
  end

在我的 Rspec 中,如何检查 build 方法在 new 操作中是否被调用?

我试过这样的

expect(assigns(:company).employees).to have_received(:build)

但我收到以下错误消息:

#<Employee::ActiveRecord_Associations_CollectionProxy:0x007fe2ca2141e8> expected to have received build, but that object is not a spy or method has not been stubbed.

我需要先给员工存根吗?

更新:

新动作的Rspec

describe "GET 'new'" do

before { get :new }

it 'assigns @domain_name' do
  expect(assigns(:domain_name)).to eq(request.host)
end

it 'assigns @company' do
  expect(assigns(:company)).to be_a_new(Company)
end

it 'renders the new template' do
  expect(response).to render_template('new')
end

结束

谢谢

【问题讨论】:

  • 能否请您发布您的 new 方法的测试块?
  • @Emu 我已经用新方法的测试块更新了我的问题。

标签: ruby-on-rails ruby rspec


【解决方案1】:

你可以这样做

之前 { expect_any_instance_of(Company.new.employees.class).to receive(:build) }

【讨论】:

  • 谢谢,效果很好。您的答案中有额外的括号“}”。我无法编辑它。
【解决方案2】:

检查结果而不是检查方法调用是否发生如何?

it 'builds an employee on @company' do
  expect(assigns(:company).employees.length).to eq(1)
  # and/or
  expect(assigns(:company).employees.first).to be_a_new(Employee)
end

【讨论】:

  • 感觉更像是模型测试而不是控制器测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
  • 2012-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多