2014-05-06 106 views
1

我想測試一些回調before_save邏輯。但是我在這個黑暗的地方堆放着我找不到解決方案。rspec測試回調工作

我有這種方法,更新一些屬性保存前:

def order_item_positions 
    Place.item_positions_reorder(item_position, city_id).each do |place| 
     new_item_position = place.item_position + 1 
     place.update_attributes(item_position: new_item_position) 
    end 
    end 

該方法做什麼,是改變上面+1位置的所有記錄! ,比我想用RSpec的這樣的事情來測試它:

describe "places order" do 
    let(:city){FactoryGirl.create(:city)} 
    let(:place){FactoryGirl.create(:place, city_id: city.id)} 
    let(:place_sec){FactoryGirl.create(:place, city_id: city.id)} 

    context "when placed before other record" do 
     it "should be placed before" do 
     place_sec.item_position = 1 
     place.item_position = 1 
     expect{ 
      ...somehow saving and triggering callback! //dont know how to do that :/ 
     }.to change(place_sec, :item_position).from(1).to(2) 
     end 
    end 
    end 

任何幫助,將不勝感激! :)

回答

1

你應該建立模型,然後將其保存,我想:

describe "places order" do 
    let!(:city) { FactoryGirl.create(:city) } 
    let!(:place) { FactoryGirl.create(:place, city_id: city.id) } 
    let!(:place_sec) { FactoryGirl.build(:place, city_id: city.id) } 

    context "when placed before other record" do 
    it "should be placed before" do 
     place_sec.item_position = 1 
     place.item_position = 1 
     expect(place_sec.save).to change(place_sec, :item_position).from(1).to(2) 
    end 
    end 
end 

你沒有在你有什麼型號提這個before_save方法order_item_positions。所以你應該保存什麼來稱呼它。只要建立這個模型,然後保存。

0

一個簡單的調用對.save應該這樣做: expect{ place_sec.save }.to change(place_sec, :item_position).from(1).to(2)