Rj01
Rj01

Reputation: 93

Rails Rspec Testing Controller New Action

I am trying to test the new action in my controller. At the moment it looks like this:

Controller

def new
  @business = Business.new
  @business.addresses.build
end

Spec

describe 'GET #new' do
  it 'assigns a new business to @business' do
    get :new
    expect(assigns(:business)).to be_a_new(Business)

  end
end

I would like to test the line '@business.addresses.build'. How do I do this?

Thanks in advance!

Upvotes: 6

Views: 4213

Answers (2)

maaachine
maaachine

Reputation: 821

Assuming build is a method, you only need test to ensure that build is called. You could do so by replacing the new Business with a mock that has an addresses attribute that expects to receive :build.

I haven't tested this, but I suspect you could do something like:

business = double('business')
addresses = double('addresses')
business.should_receive(:addresses).and_return(addresses)
addresses.should_receive(:build)
Business.stub(:new).and_return(business)

Upvotes: 1

SteveTurczyn
SteveTurczyn

Reputation: 36880

How about

expect(assigns(:business).addresses.first).to be_a_new(Address)

Upvotes: 12

Related Questions