Hi everyone I am new to Rails. My platform is Ubuntu 9.04 with Ruby 1.9.1p243 and Rails 2.3.4. I am reading SitePoint''s Simply Rails 2 book. On page 240, the author shows how to test the associations between Story and Vote model. The code is below app/models/story.rb: ---------------------------- class Story < ActiveRecord::Base validates_presence_of :name, :link has_many :votes end app/models/vote.rb: ----------------------------- class Vote < ActiveRecord::Base belongs_to :story end test/fixtures/stories.yml: ------------------------------------ one: name: My Shiny Weblog link: http://www.google.com/ two: name: Another stupid site link: http://www.apple.com/ test/fixtures/votes.yml: ---------------------------------- one: story: one two: story: one test/unit/story_test.rb: -------------------------------- def test_should_have_a_votes_association assert_equal [ votes(:one), votes(:two) ], stories(:one).votes end $ rake test:units The output of assert return failure. So I do trial-and-error fix and manage to fix it by swap the position of votes(:one) and votes(:two) order so the test method become: assert_equal [ votes(:two), votes(:one) ], stories(:one).votes Can some Rails experts explain to me why the order of vote inside the array could affect the assert_equal measure? Thank you so much
Frederick Cheung
2009-Oct-16 01:50 UTC
Re: Rails /w Ruby 1.9.1p243 - Unit Test assert_equal question
On Oct 16, 1:31 am, mojo <jonesle...-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> def test_should_have_a_votes_association > assert_equal [ votes(:one), votes(:two) ], stories(:one).votes > end > > $ rake test:units > > The output of assert return failure. So I do trial-and-error fix and > manage to fix it by swap the position of votes(:one) and votes(:two) > order so the test method become: > assert_equal [ votes(:two), votes(:one) ], stories(:one).votes > Can some Rails experts explain to me why the order of vote inside the > array could affect the assert_equal measure? > Thank you so muchbecause arrays are fundamentally ordered collections so for an array == means same elements and in the same order. Whenever you get something out of the database and there is no order clause (eg if you do Vote.all, or the association you have here) the database is free to return stuff in any order it wants to. Quite often it will be mostly the same order each time but you shouldn''t rely on that (more often than not it will something to do with the order things are stored in on disk. Fred