2012-11-07 36 views
1

我使用的是FriendlyId寶石,它在保存記錄時會生成一個slu g。它效果很好。如何在RSpec中運行規範時獲取分配的值?

我可以路由到slu like像:places/house-of-dead,完美。但是在測試時我遇到了問題。

我使用FactoryGirl來存留我要創建的參數,但我不知道如何讓生成的slug斷言如果我的路由重定向到它,我的測試是低於和(???? should be the generated slug) :

context '#create' do 
     it 'should redirect to place after created' do 
     place = FactoryGirl.attributes_for(:place) 

     post :create, { place: FactoryGirl.attributes_for(:place) } 

     response.should redirect_to places_path(slug: ????) 
     end 
    end 

我的控制很簡單:

def create 
    @place = Place.new(params[:place]) 

    # setting up who owns this place 
    @place.user = current_user 

    if @place.save 
     flash[:success] = "Place created." 

     redirect_to @place 
    else 
     render :new 
    end 
end 

正如你所看到的,我用redirect_to @place並重定向我`地方/:蛞蝓」,但是當涉及到測試重定向,我該怎麼做?

另外,我的測試方式正確/好嗎?

謝謝。

+0

'應該redirect_to place_path(place.to_param)'? – apneadiving

回答

2

你幾乎回答自己:

response.should redirect_to places_path(assigns(:place)) 

,或者如果你需要使用毛坯:

response.should redirect_to places_path(slug: assigns(:place).slug) 

更多關於assigns()https://github.com/rspec/rspec-rails#assigns

而此行

place = FactoryGirl.attributes_for(:place) 

是多餘的,因爲你永遠不使用place變量在測試的其餘部分。

相關問題