【问题标题】:RSpec test broken by pagination (Kaminari)分页破坏了 RSpec 测试(Kaminari)
【发布时间】:2011-10-28 03:55:16
【问题描述】:

我有一个视图规范正在通过,但现在已将分页(通过 Kaminari gem)添加到视图中。我仍在尝试了解 RSpec 的语法……因此,由于页面在浏览器中运行良好,因此寻求帮助以使其通过。 我知道很多人不赞成视图规格易碎(可能是因为这样的原因),但我仍然希望保持这一通过

我将一些存根帖子分配给@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

【问题讨论】:

  • 我知道您已经接受了另一个答案,但我担心通过存根您所做的只是消除了代码中的错误。上面的错误意味着您正在控制器中调用 @posts.current_page 。我可以看到@posts.first.current_page 或controller.current_page 有效,但@posts.current_page 可能不是。
  • 好点!那么,我是否应该取消控制器?我不完全确定 Kaminari 期望给current_page 打电话?!?我只知道规范 失败是因为帖子数组没有响应它......但是,你是对的,这看起来很奇怪吗? 我会暂时搁置一下,看看是否有更好的答案。
  • 能否也贴一下相关的控制器代码?

标签: ruby-on-rails ruby-on-rails-3 rspec pagination kaminari


【解决方案1】:

你应该存根这个行为,试试这个:

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

【讨论】:

  • 太棒了!谢谢!对于其他正在观看的人,我还必须以与上述:current_value 相同的方式删除其他两种方法:num_pages:limit_value...并且我为它们中的每一个返回的值是一个整数(1) .规格通过游泳...谢谢!
  • 我还必须存根total_pages。谢谢!
  • 使用 Rspec 3.1 执行 posts.stub!(:current_page).and_return(1) 抛出错误 未定义方法存根!对于数组。但是@manojlds 回答stackoverflow.com/a/8885026/936494 为我工作。
  • @Jignesh 我猜你必须用stub 替换stub!。无论如何,另一个答案更好:)
【解决方案2】:

您还可以执行以下操作:

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

【讨论】:

  • 此方法非常适合 Rails 脚手架代码。只需用 Kaminari.paginate_array(...).page(1) 和 Viola 包装生成的 stub_model 数组!工作规格。
  • Kaminari.paginate_array(...).page(1) 也适用于我的情况
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-27
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多