如何在rspec中为非杂项操作和私有方法编写测试用例?

时间:2019-08-08 06:10:55

标签: ruby-on-rails rspec

搜索方法为非粗略操作,地图为私人方法,餐厅,菜肴,位置,图片均为模型。这些模型数据包含一个数组。所以我如何编写map方法和search方法的测试用例。餐厅和位置具有HABTM关联,餐厅和菜肴也具有HABTM关联,餐厅和图片具有多态关联,并且菜肴和图片也具有多态关联

  def search
  map                                                               

   if params[:name]
        @items = Dish.search(params[:name])
   end
   if params[:price]
        @items = Dish.sortby_price(params[:price]).search(params[:name])
    end

   if params[:ratings]
        @items = Dish.sortby_ratings(params[:name])
   end
   if params[:rating]
        @items = Dish.sortby_rating(params[:rating])
    end
   if params[:category]
        @items= Dish.sortby_dietary(params[:category]).search(params[:name])
    end
  if params[:restaurant]
        @restaurants = 
        Restaurant.find(params[:restaurant])
        @items = @restaurants.dishes

     end    

  end

private
def map
    @items = Dish.search(params[:name])
    restaurants = []
    locations = []
    pictures = []

    @items.each do |d|
        @restaurants = d.restaurants
        restaurants.push(@restaurants)
        d.restaurants.each do |r|
            @pictures = r.pictures
            pictures.push(@pictures)
            @locations = r.locations
            locations.push(@locations)
        end 
    end  
    gon.restaurants = restaurants
    gon.locations = locations
    gon.pictures = pictures

    x = []
    @items.each do |d|
        @restaurants = d.restaurants
        d.restaurants.each do |r|
            x.push(r.id)
        end 
    end
    y = []
    x.each do |x|
        r = Restaurant.find(x)
        d = r.dishes.count
        y.push(d)
    end
    gon.dishes_count = y
end

1 个答案:

答案 0 :(得分:0)

有人说不需要测试私有方法。但是我在一家公司工作,我们会测试私有方法。

对于您的情况,我建议您这样做:

  1. 测试方法#map与操作#search分开。您需要检查gon, @items, @restaurants, @pictures, @locations对象是否正确填充。 您可以使用方法#send测试私有方法。

示例:

describe '#map' do
  subject { controller.send(:map) }

  # you would need to stub params method
  before { allow(controller).to receive(:params).and_return({ name: 'my name' }) }

  it { expect(controller.instance_variable_get(:@items)).to include/not be_blank/... }
end
  1. 测试方法#search而不实际调用方法映射。

示例:

describe '#search' do

  before { allow(controller).to receive(:map) }

  # you can set different context where you test cases with different parameters
  context 'when params[:name] and params[:ratings] exist' do
    before { get :search, { name: '...', ratings: '...' } }

    it {...}
  end
end