rspec更改属性不会更改其他记录

时间:2014-05-08 08:11:08

标签: ruby-on-rails rspec

我有测试的这个问题,我有逻辑重新排序位置,例如,如果我有1,2,3和我给3位置1比1,2将成为2,3。现在我试图测试这个,但我似乎无法弄清楚这一点!

这是我的测试:

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

调用重新排序的方法

1 个答案:

答案 0 :(得分:2)

Okey谷歌搜索和堆栈溢出我发现必须重新加载对象,以获得我需要的结果。像这样:

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