【发布时间】:2014-08-07 17:36:49
【问题描述】:
我想测试控制器方法,但找不到使用 order 和 search 的测试方法示例。 这是我的控制器:
class Admin::HotelsController < Admin::BaseController
helper_method :sort_column, :sort_direction
def index
@hotels = Hotel.search(params[:search], params[:search_column]).order(sort_column + ' ' + sort_direction)
end
def show
@hotel = Hotel.find(params[:id])
end
def update
@hotel = Hotel.find(params[:id])
if @hotel.update_attributes(hotel_params)
redirect_to admin_hotels_path
else
render(:edit)
end
end
private
def hotel_params
params.require(:hotel).permit(:title, :description, :user_id, :avatar, :price, :breakfast, :status, address_attributes: [:state, :country, :city, :street])
end
def sort_column
Hotel.column_names.include?(params[:sort]) ? params[:sort] : 'created_at'
end
def sort_direction
%w[asc desc].include?(params[:direction]) ? params[:direction] : 'asc'
end
end
这是对该控制器的测试。
require 'rails_helper'
describe Admin::HotelsController do
login_admin
describe 'GET index' do
it 'render a list of hotels' do
hotel1, hotel2 = create(:hotel), create(:hotel)
get :index
expect(assigns(:hotels)).to match_array([hotel1, hotel2])
end
end
describe 'GET show' do
it 'should show hotel' do
@hotel = create(:hotel)
get :show, { id: @hotel.to_param, template: 'hotels/show' }
expect(response).to render_template :show
end
end
end
我不知道如何测试索引方法。请帮助或给我一个链接,其中包含有关此信息的信息。谢谢!
【问题讨论】:
-
尝试使用
eq而不是match_array。 -
谢谢,它们的不同之处在于,即使是部分匹配,match_array 也会返回 true?
-
match_array是contain_exactly的替代形式,它不关心顺序。
标签: ruby-on-rails ruby rspec rspec-rails