I have a TopicsController, with new action:
def new
@section = Section.find(params[:section_id])
@topic = @section.topics.build
end
While trying to test this simple behavior, I ended up with quite ugly and robust mock structure
describe "#new" do
it "builds a topic with a given section" do
new_topic = mock_model(Topic)
topics = mock('topics')
topics.should_receive(:build).and_return(new_topic)
section = mock_model(Section)
section.should_receive(:topics).and_return(topics)
Section.should_receive(:find).with("1").and_return(section)
get :new, :section_id => 1
assigns[:topic].should == new_topic
end
end
I’d like to make this code simpler, but I don’t see how. I can’t get rid of the @section mock, and it has to return something specific on the chained .topics.build call to allow me to set an expectation.
Is there any simpler way to do this? I’m using RSpec 2.7.
1 Answer