2015-12-22 83 views
0

我在下面的代码片段我CompaniesControllerRspec的用于构建嵌套属性

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 

感谢

+0

请问您可以发布** **新方法的测试块吗? – Emu

+0

@Emu我已经用新方法的测试块更新了我的问题。 – Reboot

回答

3

你可以像下面这样做

before { expect_any_instance_of(Company.new.employees.class).to receive(:build) }
+0

谢谢伟大的作品。答案中有额外的括号'}'。我无法编辑它。 – Reboot

+0

谢谢,删除它 – user3409950

1

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

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 
+0

感觉更像是模型测试而不是控制器测试。 – Reboot