6

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!

3
  • I think you need to create a mock object.. Commented Apr 30, 2014 at 12:08
  • 1
    Try to check presence of @business.addresses stackoverflow.com/questions/6084346/… Commented Apr 30, 2014 at 12:12
  • In what situation, this piece of code will fail? Commented Apr 30, 2014 at 14:10

2 Answers 2

12

How about

expect(assigns(:business).addresses.first).to be_a_new(Address)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

4 Comments

I wouldn't do this, because it's testing implementation rather than result. What if you changed build to be new? The result is the same, but your test would break.
That's true! It's a very brittle test, but he did ask how to test that specific line. Perhaps the bigger question is why that line is even in the controller. Should it be moved to the constructor?
Sorry, I am new to rails. I understand what a constructor is however not sure where it should be implemented using the mvc pattern. Would it be put in the model and called from the controller?
Inside your definition for Business, you can define a function called initialize that acts as the endpoint for Business.new(...). In your case, it might contain addresses.build if you know that all business instances should build addresses.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.