[rspec-users] rspec controller action list

David Chelimsky dchelimsky at gmail.com
Thu Feb 28 09:05:54 EST 2008

On Thu, Feb 28, 2008 at 3:54 AM, Namrata Tiwari <lists at ruby-forum.com> wrote:
> This action will list all the articles according to city. Please, can
>  some one guide me through this spec.
>  def list
>   @articles = find_city.articles.paginate :all,  :page => params[:page]

This line has what we call a train wreck. Don't be alarmed! It sounds
dramatic, but that's a common term for a series of objects strung
together with dots:

find_city returns the first object, on which articles gets called.
articles returns the second object, on which paginate is called.

As soon as you have that second dot you have a train wreck.

More below ...

>  , :order
>   => "live_on DESC", :conditions => { :type_for => "blog" }
>  end
>  it "should list all articles" do
>    get :list

Here the action is called before setting up all the expectations. When
using mocks and stubs, they have to be set up before the action.

>    controller.stub!(:find_city)

Because the code has find_city returning an object, the stub has to
return an object. Because the object returned by find_city gets sent
paginate, it must be able to respond to that so it needs to either be
the kind of object (an AssociationProxy) or a substitute.

>    controller.should_receive(:find_city)
>    controller.stub!(:articles)
>    controller.should_receive(:articles)
>     articles.should_receive(:paginate).and_return(@articles)
>     response.should render_template('articles/list')
>  end

Given the code above, the spec needs to do this:

articles = mock("articles")
  with(order => "live_on DESC", :conditions => { :type_for => "blog" })
get :list


>  I get the following error when I run the spec.
>  NameError in 'ArticlesController should list all articles'
>  undefined local variable or method `articles' for
>  #<Spec::Rails::Example::Contro
>  llerExampleGroup::Subclass_1:0xa7b57dc>
>  spec/controllers/articles_controller_spec.rb:212:
>  spec/controllers/articles_controller_spec.rb:3:
>  --
>  Posted via http://www.ruby-forum.com/.
>  _______________________________________________
>  rspec-users mailing list
>  rspec-users at rubyforge.org
>  http://rubyforge.org/mailman/listinfo/rspec-users

More information about the rspec-users mailing list