我第一次使用Ransack进行搜索。 我有这样的控制器
class CoursesController < ApplicationController
def search
@q = Post.joins(:events).where(status: true, publish: true)
.where("events.status = 'available'")
.search(params[:q])
@courses = @q.result.includes(:tagnames).to_a.uniq
render :index
end
end
在route.rb中,它包含路径
get 'posts/autocomplete_tag_or_subcategory', to: 'posts#get_suggestion_keywords', as: :list_suggestion
和
resources :courses, only: [:search] do
collection do
match 'search' => 'courses#search', via: [:get, :post], as: :search
end
end
在视图中,我们的表单包含此字段
= search_form_for @q, url: search_courses_path, method: :post do |f|
= f.search_field :title_or_description_or_tagnames_title_cont, { data: {autocomplete: list_suggestion_path } }
一切似乎都正常。 问题是,我不知道如何传递该控制器的测试用例的参数。 我试过了:
it "get all records match the key words" do
get :search, q: {title_or_description_or_tagnames_title_cont: 'math'}
expect(assigns_courses).to include math_course
end
整个rspec文件
RSpec.describe CoursesController , type: :controller do
describe "#search" do
let!(:search_params) { 'math' }
let!(:tutor) { create :user, user_type: :tutor }
let!(:math_course) { create(:post, title: "math", user_id: tutor.id) }
let(:assigns_courses) { assigns(:courses) }
before { @request.env['devise.mapping'] = Devise.mappings[:user] }
before { sign_in tutor }
it "get all records match the key words" do
get :search, q: {title_or_description_or_tagnames_title_cont: 'math'}
expect(assigns_courses).to include math_course
end
end
end
这是Post模型
class Post < ActiveRecord::Base
scope :published, -> { where(status: true, publish: true) }
scope :get_post_by_tag_name, -> (tag_name) { where("lower(tags) LIKE ? ", "%#{ tag_name.downcase }%") }
belongs_to :category
belongs_to :sub_category
belongs_to :level
belongs_to :user
has_many :events, dependent: :destroy
.....
活动模型
class Event < ActiveRecord::Base
extend Enumerize
enumerize :status, in: [:available, :booked, :hidden], default: :available
belongs_to :post
end
但看起来不正确,因为它没有显示我想看到的内容。 请给我一些帮助来通过这个测试用例的参数。
非常感谢。
答案 0 :(得分:1)
宝石搜索应该没有错误,你的代码对我来说是正确的。
我建议您再次以get :search
运行测试,并首先查看问题所在(例如,可能未设置发布等)。