Rails - 如何测试需要Gem实例的视图(f.e. wice_grid)

时间:2013-11-21 16:42:54

标签: ruby-on-rails rspec rubygems ruby-on-rails-4 rspec-rails

我需要为我们使用wice_grid的视图文件编写测试。我们现在遇到的问题是测试失败,因为视图需要一个这样的实例。

  1) admin/shops/index renders a list of admin/shops
 Failure/Error: render
 ActionView::Template::Error:
   WiceGrid: The first argument for the grid helper must be an instance of the WiceGrid class
 # ./app/views/admin/shops/index.html.erb:40:in `_app_views_admin_shops_index_html_erb___340103790847020275_34309580'
 # ./spec/views/admin/shops/index.html.erb_spec.rb:12:in `block (2 levels) in <top (required)>'

问题是:“我怎样才能获得Gem实例将其传递给规范中的视图文件?”

测试文件

require 'spec_helper'

describe "admin/shops/index" do
  before(:each) do
    assign(:admin_shops, [
      stub_model(Shop),
      stub_model(Shop)
    ])
  end

  it "renders a list of admin/shops" do
    render
    # Run the generator again with the --webrat flag if you want to use webrat matchers
  end
end

这是视图文件

<%= grid(@grid, upper_pagination_panel: false) do |g| css_class = 

        g.column name: "Id", attribute: "id"

        g.column name: "Country", attribute: "country_id"

end -%>

1 个答案:

答案 0 :(得分:3)

在测试中需要wice网格:

编辑:测试中还包含wice_grid控制器:

require 'spec_helper'
require 'wice_grid'

describe "admin/shops/index" do
   include Wice::Controller # this will add the initialize_grid method
   # ...

然后在测试的before(:each)中将@grid var分配给新的wice_grid

describe "admin/shops/index" do
  include Wice::Controller

  before(:each)do
    assign(:grid, initialize_grid(Shop))
  end

  # ... your tests

当您initialize_grid(YourModel)分配@grid时,ActionController::Base看起来与控制器中的内容相同。

编辑:我想出的方法是阅读wice_grid来源,从这个文件开始:https://github.com/leikind/wice_grid/blob/rails3/lib/wice_grid.rb - 在第36行你可以看到wice如何将自己包含在initialize_grid中。这是您在控制器中使用{{1}}方法的方法。所以它也适用于你的测试。