代码之家  ›  专栏  ›  技术社区  ›  Mike Sutton

为什么在我的单元测试中查找(:last)失败?

  •  0
  • Mike Sutton  · 技术社区  · 15 年前

    我在Rails中有一对多的关系:

    class User < ActiveRecord::Base
      has_many :activities, :order => "added_at DESC"
    
    
    class Activity < ActiveRecord::Base
      belongs_to :user
    

    我有一个活动的方法:

    def self.test_message(user, message)
      user.activities << Activity.create do |activity|
        activity.message = message
        activity.added_at = Time.now
      end    
    end
    

    以及以下单元测试:

    require 'test_helper'
    
    class ActivityTest < ActiveSupport::TestCase
    
      def test_test_message
        #From fixture
        alice = User.find_by_name("alice")
        assert_equal 0, alice.activities.count
    
        Activity.test_message(alice, "Hello")
        assert_equal 1, alice.activities.count
    
        Activity.test_message(alice, "Goodbye")
        assert_equal 2, alice.activities.count
        assert_equal "Hello", alice.activities.find(:first).message
    
        #The following line fails with: Goodbye expected but was Hello
        assert_equal "Goodbye", alice.activities.find(:last).message,
        acts = alice.activities
        assert_equal 2, acts.count
        assert_equal "Goodbye", acts[1].message
      end
    end
    

    在指定的线路上失败了,但我不知道为什么。

    另外,使用activities.find(:last)在使用开发环境时有效,但仅在测试环境下失败。我已经删除并重建了数据库。

    1 回复  |  直到 15 年前
        1
  •  0
  •   Kyle    15 年前

    http://weblog.jamisbuck.org/2007/1/18/activerecord-association-scoping-pitfalls

    def Activity.by_added_at
      find :all, :order => 'added_at DESC'
    end