【问题标题】:Why find(:last) fail in my unit tests?为什么 find(:last) 在我的单元测试中失败?
【发布时间】:2009-10-01 14:34:41
【问题描述】:

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

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


class Activity < ActiveRecord::Base
  belongs_to :user

我在Activity中有一个方法:

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

在指示的行上失败了,但我不知道为什么。

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

【问题讨论】:

  • 在问题行之前,“puts alice.activities.inspect”打印什么?
  • 另外,尝试按“created_at”专门排序,看看是否有同样的问题
  • 您也不必执行 find(:first) 或 find(:last),只需执行 alice.activities.first 或 alice.activities.last =)
  • 你在这里测试 ActiveRecord,而不是你自己的代码。

标签: ruby-on-rails one-to-many relationships


【解决方案1】:

这似乎是在您的关联声明中使用 :order 标志的问题。这篇文章并不是您所遇到的确切情况,但一般建议您不要采用这种做法:

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

(我不确定这些建议是否仍然相关,但在我进行以下更改之前,我在 Rails 2.3.3 中看到的行为与您相同。)

我在本地设置了您的应用,并尝试通过添加来应用评论 #4 中的技术

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

并将测试中的 find(:first) 和 find(:last) 更改为 .by_added_at.first 和 .by_added_at.last,这样会返回更稳定的结果。

另一个建议——你的测试现在相当大。您可以考虑将其拆分为多个测试,每个测试最多测试一个或两个条件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    相关资源
    最近更新 更多