0

Railsには1対多の関係があります。

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

示された行で失敗しますが、理由がわかりません。

また、activitys.find(:last)の使用は、開発環境を使用する場合に機能しますが、テスト環境でのみ失敗します。データベースを削除して再構築しました。

4

1 に答える 1

0

これは、関連付け宣言で: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に変更すると、より安定した結果が返されます。

もう1つの提案-あなたのテストは今かなり大きいです。複数のテストに分割することを検討してください。各テストは、最大で1つまたは2つの条件をテストします。

于 2009-10-01T16:11:05.453 に答える