有2个问题阻止了我的测试通过:
对于记录,以下语法有效。
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