由于分页(Kaminari)导致 RSpec 测试失败

24

我有一个视图规范(View Spec),它以前是通过的,但现在已经破了,原因是在视图中添加了分页(Kaminari gem)。我还在尝试弄清楚 RSpec 的语法...所以希望得到帮助,使其通过测试,因为在浏览器中页面可以正常工作。我知道很多人不喜欢视图规范(View Spec)因为它们很脆弱(可能是出于这样的原因),但我仍然希望保持这个规范通过测试

我将一些存根(post)赋值给 @posts 数组。但数组并没有响应 current_page。那么我该如何在 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

1
我知道你已经接受了另一个答案,但我担心你通过做你所做的存根来消除了代码中的一个错误。上面的错误意味着你在控制器中调用了@posts.current_page。我可以看到@posts.first.current_page或controller.current_page是有效的,但@posts.current_page可能不是。 - Luke Cowell
好的点子!那么,也许我应该把控制器存根起来吗?我不太确定Kaminari希望在哪里调用current_page?!? 我只知道这个规范曾经失败,因为帖子数组没有响应它...但是,你是对的,这似乎很奇怪? 我会把这个问题保持开放状态一段时间,看看是否有更好的答案出现。 - Meltemi
你能否也发布相关的控制器代码? - Luke Cowell
2个回答

47

您也可以像下面这样做:

assign(:posts, Kaminari.paginate_array([
        Factory.stub(:post),
        Factory.stub(:post)
      ]).page(1))

2
这种方法非常适合Rails脚手架代码。只需用Kaminari.paginate_array(...)包装生成的stub_model数组,并使用.page(1),就可以轻松实现工作规范。 - scarver2
1
Kaminari.paginate_array(...).page(1) 在我的情况下也可以工作。 - Amit Patel

17

你应该对行为进行存根(Stub),尝试这样做:

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

3
太棒了!谢谢!对于其他观看的人,我还必须像上面的:current_value方法一样以同样的方式去除另外两个方法:num_pages:limit_value,并且我为它们返回的值都是整数(1)。测试顺利通过了......谢谢! - Meltemi
1
我还得存根 total_pages。谢谢! - Matt Connolly
使用 Rspec 3.1 进行 posts.stub!(:current_page).and_return(1) 操作时,会抛出 Undefined method stub! for Array 错误。但是 @manojlds 的答案 https://dev59.com/jmw05IYBdhLWcg3wsz7N#8885026 对我很有帮助。 - Jignesh Gohel
@Jignesh 我猜你需要用 stub 替换 stub!。不管怎样,另一个答案更好 :) - apneadiving

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接