mercredi 24 juin 2015

Testing Rails models that affect other models

I'm making a Workflowy clone. Basically, it's a to-do list app that lets you nest items within other items.

In my app, each Item has a Placing to keep track of its place in the list. Along with an item_id, each Placing has a parent_id and place which must form a unique combination.

I've got a working change_place method that updates a Placing with a new place. It also updates all sibling Placings whose places need to be shifted to avoid conflicting place numbers. I've tested it using the browser and the console, and I've successfully used something like placing_a.change_place(4) to change a list from this (numbers representing places):

  1. item_a (placing_a)
  2. item_b (placing_b)
  3. item_c (placing_c)
  4. item_d (placing_d)

...into this:

  1. item_b (placing_b)
  2. item_c (placing_c)
  3. item_d (placing_d)
  4. item_a (placing_a)

Yet, I can't write a passing test in Minitest for this behavior. The Placing that I use to call change_place will have the place I expect, but the Placings that should shift as a result just stay the same. I don't see any reason why this shouldn't work: (note siblings here includes all sibling placements, even self)

test "inserting item after siblings should move them up" do
  siblings_to_be_moved = @placing1.siblings.select do |sibling| 
    sibling.place > @placing1.place
  end
  assert_difference siblings_to_be_moved.map(&:place).map(&:to_s), -1 do
    @placing1.change_place @placing1.siblings.length
  end
end

I tried simplifying things by testing one sibling place at a time, but they just won't change in the tests even though I know my change_place method is working. Is there some kind of quirk about Rails unit tests that might be preventing my tests from passing? I feel like I'm missing something major here, but I don't have the vocabulary to Google it. :/ Any help would be appreciated!

Aucun commentaire:

Enregistrer un commentaire