2015-12-22 58 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