我在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(:最后一个)使用开发环境时的作品,但只有在测试环境下失败。我已经下降并重建数据库。

有帮助吗?

解决方案

这似乎是与使用的问题:在你的公会声明顺序标志。这个职位是不是您遇到的确切情况,但建议不要在一般的做法:

http://weblog.jamisbuck.org/2007 / 1/18 / ActiveRecord的关联-作用域-陷阱

(我不知道,如果这些建议仍然相关,但我看到了相同的行为,你的Rails 2.3.3,直到我做了以下的变化。)

我设置应用在本地,并试图通过添加应用从评论#4的技术

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

和改变你的查找(:第一)和发现(:最后一个)。在测试中.by_added_at.first和.by_added_at.last,它返回更稳定的结果

另外一个建议 - 你的测试是相当大的现在。你可能会考虑拆分出来到多个测试,它们各自在大多数测试中的一个或两个条件。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top