質問

私は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

指定された行に失敗しますが、私は、なぜうまくいかないことができます。

(:最後の)

また、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

とあなたの検索を変更する(:最初)とfind(:最後)。より安定した結果を返し.by_added_at.firstと.by_added_at.lastするテストで、

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top