2014-05-08 52 views
1

我有这个问题与测试,我有重新排序位置的逻辑,例如,如果我有1,2,3,我给3位置1比1,2将成为2, 3.现在我试图测试这个,但我似乎无法弄清楚这一点!rspec改变属性不会改变其他记录

这里是我的测试:

describe "order change" 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)} 
    let(:place_th){FactoryGirl.create(:place, city_id: city.id)} 

context "when editing record" do 
     it "should go up and change middle records" do 
     place 
     place_sec 
     place_th 
     expect{ 
      place_id = Place.find(place.id) 
      place_id.update_attributes(item_position: 3) 
     }.to change(Place.find(place_sec.id), :item_position).from(2).to(1) 
     end 
    end 

这是不行的,我需要为此做些什么工作?重新排序的方法被称为回调before_save

+0

'place \ n place_sec \ n place_th'这个你调用真正创建记录吗?那么,'cite'创造了什么地方? (我不太清楚)“let”和“let!”之间有区别,也许你应该使用最后一个。 – zishe

+1

嗯,我试过,我会阅读更多,但总之没有任何改变! – user2945241

回答

2

Okey谷歌搜索和stackoverflowing周围我发现必须reaload对象来获得我需要的结果。类似这样的:

describe "order change" 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)} 
    let(:place_th){FactoryGirl.create(:place, city_id: city.id)} 

context "when editing record" do 
     it "should go up and change middle records" do 
     place 
     place_sec 
     place_th 
     expect{ 
      place.update_attributes(item_position: 3) 
      place_sec.reload 
     }.to change{place_sec.item_position}.from(2).to(1) 
     end 
    end