2014-03-19 106 views
0

我需要在我的控制器中測試自動完成操作。我的測試只需要期望計數返回,但我無法弄清楚如何做到這一點。Rspec測試自動完成

這裏是方法本身:

def autocomplete 
    respond_to do |format| 
     format.json do 
     model_suggestions = Vehicle.select([:model, :make]).where('make IS NOT NULL AND model IS NOT NULL').reorder('').order("make ASC, model ASC") 

     if params.has_key? :model 
      model_suggestions = model_suggestions.group(:model) 
     else 
      model_suggestions = model_suggestions.group(:make) 
     end 

     unless params[:model].blank? 
      model_suggestions = model_suggestions.where('model LIKE ?', "%#{params[:model]}%") 
     end 

     unless params[:make].blank? 
      model_suggestions = model_suggestions.where('make LIKE ?', "%#{params[:make]}%") 
     end 

     model_list = {model: [], make: []} 

     model_suggestions.each do |car| 
      model_list[:make] << car[:make].strip 
      model_list[:model] << car[:model].strip 
     end 

     model_list[:make].uniq! 
     model_list[:model].uniq! 

     render json: model_list 
     end 
    end 
    end 

這裏是路線:

get :autocomplete, constraints: {format: 'json'} 

這裏是RSpec的測試我所需要的。我想不出任何事情。我對rails和TDD非常陌生。所以請不要評價我如此苛刻

describe "GET #autocomplete" do 
    before do 
     FactoryGirl.create(:vehicle, make: "AUDI", model: "A4") 
     FactoryGirl.create(:vehicle, make: "BMW", model: "M5") 
     FactoryGirl.create(:vehicle, make: "BMW", model: "M3") 
    end 

    it "responds to with 2 makers" do 
     get :autocomplete, :format => :json #giving param make: "BMW" 
     # expect count 2 
    end 

    end 

我怎麼能做到這一點???非常感謝:)

回答

0

你可以檢查響應的身體:

it "responds to with 2 makers" do 
    get :autocomplete, :format => :json #giving param make: "BMW" 
    res = JSON.parse(response.body) 
    # assertions on res 
end 

如果你這樣做了很多,考慮添加輔助方法或類似的保持乾燥的東西。

+0

非常感謝soo,我覺得這裏已經有幾個小時了:) – user2945241