2012-05-30 31 views
1

回報率控制器:意外測試失敗使用RSpec和工廠

def destroy 
    Page.find(params[:id]).destroy 
    @pagechildren = Page.where("parent_id = ?", params[:id]) 
    @pagechildren.update_all({parent_id: -1}) if @pagechildren.count > 
0 
    flash[:success] = 
t('activerecord.errors.controllers.message.attributes.page.page_destroy_suc cess') 
    redirect_to pages_path 
    end 

測試RSpec的

 it "should remove parent_id from children" do 
     @page2 = Factory(:page) 
     @pagechild = Factory(:page) 
     @pagechild[:parent_id] = @page2.id 
     lambda do 
      delete :destroy, :id => @page2 
     end.should 
change(@pagechild, :parent_id).from(@page2.id).to(-1) 
     end 

代碼正常(),但

Кодвсекорректнообрабатывает(漁獲 '身份證'刪除頁面,併爲所有 孩子parent_id更改爲-1)。但rspec測試失敗。

廠:

Factory.define :page do |page| 
    page.name "Name example page" 
    page.title "Title example page" 
    page.content "Content example page" 
    page.metadescription "metadescription example page" 
    page.metakeywords "metakeywords example page" 
    page.head "head example page" 
    page.ismenu true 
    page.order_id -1 
    page.parent_id -1 
end 

測試是紅色=( 什麼是錯的

+0

RSpec的測試說:PARENT_ID不受-1 – Danko

+0

改變請縮小其斷言失敗,什麼是由被測試的代碼。 –

+0

控制器動作的代碼太多,請嘗試將其移動到模型中,如下所示:'Page.find(params [:id])。destroy_unsetting_children'。順便說一句,這是什麼數據庫需要將外鍵設置爲「-1」而不是「NULL」? – tokland

回答

2

。你的代碼會更新數據庫中的所有子項,但不會更新你的測試實例:) 試試這個:

it "should remove parent_id from children" do 
     @page2 = Factory.create(:page) 
     @pagechild = Factory.create(:page) 
     @pagechild[:parent_id] = @page2.id 
     delete :destroy, :id => @page2 
     @pagechild.reload.parent_id.should == -1 
end 
+0

非常感謝!很酷,它的工作 – Danko

+0

很高興,接受答案:) –

0

嘗試

delete :destroy, :id => @page2.id 

並顯示,如果它仍然無法正常工作rspec的輸出