在编写Minitest时如何格式化Ransak Params?

时间:2017-05-01 13:00:24

标签: ruby-on-rails parameters minitest ransack

修改

有2个问题阻止了我的测试通过:

  1. 我忘了我的设置中有3个俱乐部(不是2个)包含字母'b'。
  2. 我的clubs.yml夹具包含一个块,可以创建100个额外的球杆。由于我使用的是will_paginate,因此并非所有的俱乐部都出现在1个结果页面上。
  3. 对于记录,以下语法有效。

    get clubs_path, params: { q: { name_cont: "at" } }
    

    原始问题

    我正在为我的搜索查询撰写Minitest,但不知道如何格式化参数

    下面是我写的Minitest失败,应该传递。当我在浏览器中实际测试我的应用程序时,按预期工作,并搜索名称。我认为这些问题与我如何传递 params

    有关

    Minitest失败

    # name search
    test "should display correct clubs on name search" do
      # go to search page
      get clubs_path
      assert_template 'clubs/index'
      # search for "b"
      get clubs_path, params: { "q[name_cont]" => 'b' }
      assert_template 'clubs/index'
      # ensure all clubs with "b" in their name appear
      assert_select "a[href=?]", club_path(@quincy), count: 0
      assert_select "a[href=?]", club_path(@worcester), count: 0
      assert_select "a[href=?]", club_path(@brtc), count: 1
      assert_select "a[href=?]", club_path(@baa), count: 1
    end
    

    控制器

    def index
      # if there is data in origin field
      if params[:origin].present? && params[:distance].present?
        @q = Club.near(params[:origin], params[:distance], order: :location).order(created_at: :desc).paginate(page: params[:page]).ransack(params[:q])
        @clubs = @q.result(distinct: true)
      # if there isn't data in the origin and distance fields. show everything
      else
        @q = Club.order(created_at: :desc).paginate(page: params[:page]).ransack(params[:q])
        @clubs = @q.result(distinct: true)
      end
    end
    

    搜索表单

    <%= search_form_for @q, url: yield(:search_path) do |f| %>
      ...
      <div class="form-group"><!-- name -->
        <%= f.label :name_cont %>
        <%= f.search_field :name_cont, class: "form-control" %>
      </div><!--/ name -->
      ...
    <% end %>
    

    我也试过以下,但仍然没有运气。

    get clubs_path, params: { q: { name_cont: "b" } }
    get clubs_path, q: { name_cont: 'b'}
    

    奇怪的是,下面的minitest工作正常。我不确定这是否是编写参数的首选方法,但测试确实通过了。

    get clubs_path, params: { "q[club_categories_id_eq_any][]" => @road_racing.id, distance: 10, origin: "02169" }
    

    工作时间最短

    # category search
    test "should display correct clubs on category search" do
      # go to search page
      get clubs_path
      # ensure page loads
      assert_template "clubs/index"
    
      # fill out form with quincy proximity, searching for road_racing
      get clubs_path, params: { "q[club_categories_id_eq_any][]" => @road_racing.id, distance: 10, origin: "02169" }
      # ensure quincy is the only club
      assert_select "a[href=?]", club_path(@quincy), count: 1
      assert_select "a[href=?]", club_path(@worcester), count: 0
    end
    

0 个答案:

没有答案