我对使用rspec编写测试有点新意,我正在试图弄清楚如何正确地为此定义编写此测试。该定义只是搜索用户,如果已经添加,则不会返回它们。定义有效,我只想正确测试它。
这是我在控制器中得到的东西:
class SearchController < ApplicationController
ROWS = 9
def name_search
page = params[:page].present? ? params[:page] : 1
query = params[:query].present? ? params[:query] : params[:'search-keywords']
approved_user_ids = Approval.where(user_id: logged_in_user.id).pluck(:approved_user_id)
search_results = User.where(['name LIKE :query OR operator_id LIKE :query', { query:
"%#{query}%" }]).where.not(id: approved_user_ids).order(:name)
page_count = (search_results.count / ROWS.to_f).ceil
paginated_search_results = search_results.limit(ROWS).offset(ROWS * (page.to_i - 1))
respond_to do |format|
format.html do
if request.xhr?
render partial: 'layouts/search_results_modal', locals: { search_results: paginated_search_results,
page_count: page_count, page: page, query: query
}, layout: false, status: 200
end
end
end
end
end
并且在测试中:
context 'when a user is added' do
subject { controller.name_search }
let(:approved_user) { double(map: double) }
before do
allow(controller).to receive(:logged_in_user).with(no_args).and_return(logged_in_user)
allow(User).to receive(:where).and_return(empty_collection)
end
it "name search receieves correct results" do
expect(Approval).to receive(:where).with( { user_id: logged_in_user.id } ).and_return(approved_user)
expect(User).to receive(:where).with('name LIKE ? OR operator_id LIKE ?', "%#{ query }%", "%#{ query }%")
subject
end
end
我是否正在为此编写测试?知道如何正确测试这个定义“name_search”吗?