我在 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) 有效,但仅在测试环境下失败。我已经删除并重建了数据库。