23

I have a view spec that was passing but is broken now that pagination (via Kaminari gem) has been added to the view. I'm still trying to get my head around RSpec's syntax...so looking for help in getting this to pass as the page works fine in the browser. I'm aware that many people frown on view specs for being brittle (probably for reasons like this) but I still would like to keep this one passing

I am assigning some stubbed posts to the @posts array. But arrays don't respond to current_page. So how should I handle this in RSpec?

Failures:

  1) posts/index.html.haml renders a list of posts
     Failure/Error: render
     ActionView::Template::Error:
       undefined method `current_page' for #<Array:0x000001028ab4e0>
     # ./app/views/posts/index.html.haml:31:in `_app_views_posts_index_html_haml__291454070937541541_2193463480'
     # ./spec/views/posts/index.html.haml_spec.rb:39:in `block (2 levels) in <top (required)>'

spec/views/posts/index.html.haml_spec.rb:

require 'spec_helper'

describe "posts/index.html.haml" do
  before(:each) do
    ...
    assign(:posts, [
      Factory.stub(:post),
      Factory.stub(:post)
    ])    
    view.should_receive(:date_as_string).twice.and_return("June 17, 2011")
    ...
  end

  it "renders a list of posts" do
    render
    rendered.should have_content("June 17, 2011")
    ...
  end
end
4

2 回答 2

46

You can also do something like below:

assign(:posts, Kaminari.paginate_array([
        Factory.stub(:post),
        Factory.stub(:post)
      ]).page(1))
于 2012-01-16T19:08:34.273 回答
17

You should stub the behavior, try this:

before(:each) do
  ...
  posts = [Factory.stub(:post), Factory.stub(:post)]
  posts.stub!(:current_page).and_return(1)
  posts.stub!(:total_pages).and_return(2)
  assign(:posts, posts)    
  view.should_receive(:date_as_string).twice.and_return("June 17, 2011")
  ...
end
于 2011-08-16T15:10:09.097 回答