2014-05-06 138 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)