ruby - Problem on Rails fixtures creation sequence -


i reading book rails sitepoint , given these models:

story.rb

class story < activerecord::base     validates_presence_of :name, :link     has_many :votes         def latest             find :all, :order => 'id desc', :limit => 3         end     end      def to_param         "#{id}-#{name.gsub(/\w/, '-').downcase}"     end end 

vote.rb

class vote < activerecord::base     belongs_to :story end 

and given fixtures

stories.yml

one:   name: mystring   link: mystring  two:   name: mystring2   link: mystring2 

votes.yml

one:   story: 1  two:   story: 1 

these tests fail:

story_test.rb

def test_should_have_a_votes_association     assert_equal [votes(:one),votes(:two)], stories(:one).votes   end  def test_should_return_highest_vote_id_first     assert_equal votes(:two), stories(:one).votes.latest.first   end 

however, if reverse order of stories, first assertion , provide first vote first assertion, passes

story_test.rb

def test_should_have_a_votes_association     assert_equal [votes(:two),votes(:one)], stories(:one).votes   end    def test_should_return_highest_vote_id_first     assert_equal votes(:one), stories(:one).votes.latest.first   end 

i copied in book , have not seen errata this. first conclusion fixture creating records bottom top declared, doesn't make point

any ideas?

edit: using rails 2.9 running in rvm

your fixtures aren't getting ids 1, 2, 3, etc. you'd expect - when add fixtures, ids based (i think) on hash of table name , fixture name. humans, random numbers.

rails can refer other fixtures name easily. example, fixtures

#parents.yml vladimir:   name: vladimir ilyich lenin  #children.yml joseph:   name: joseph vissarionovich stalin   parent: vladimir 

actually show in database like

#parents.yml vladimir:   id: <%= fixture_hash('parents', 'vladimir') %>   name: vladimir ilyich lenin  #children.yml joseph:   id: <%= fixture_hash('children', 'joseph') %>   name: joseph vissarionovich stalin   parent_id: <%= fixture_hash('parents', 'vladimir') %> 

note in particular expansion parent: vladimir parent_id: <%= ... %> in child model - how rails handles relations between fixtures.

moral of story: don't count on fixtures being in particular order, , don't count on :order => :id giving meaningful results in tests. use results.member? objx repeatedly instead of results == [obj1, obj2, ...]. , if need fixed ids, hard-code them in yourself.

hope helps!

ps: lenin , stalin weren't related.


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -