3

初期化に複数のパラメーターを持つモデルがあり、そのうちの 1 つはインスタンス化時にモデルのメソッドで使用されます。

def initialize(sha, message, repo)
    sha = commit.sha
    message = commit.message
    associate_with(repo)
end

そして、これらのパラメータを使用して初期化するファクトリを作成しようとしていますが、wrong number of arguments実行しようとするとエラーが発生します:

FactoryGirl.define do
  factory :commit do
    intialize_with { new("test_sha", "test_msg", "test_repo") }
  end
end

しかし、これは私に与えますwrong number of arguments (0 for 3)。に複数の引数を渡すことはできませんinitialize_withか?

4

2 に答える 2

5

それがあなたが呼んでいるものであるため、クラスの上記のinitializeメソッドですCommitCommit.new("test_sha", "test_msg", "test_repo")

私はそれが当てはまるとは思わないので、これはCommit.

FactoryGirl.define do
  factory :commit do
    sha "test_sha"
    message "test_message"
    repo "test_repo"
    intialize_with { new(sha,message,repo) }
  end
end

これは呼び出します

Commit.new({sha: "test_sha", message: "test_message", repo: "test_repo"})

次に、他のオブジェクトを次のように正しく初期化する必要があります

FactoryGirl.define do
  factory :my_other_class do
    initialize_with { new('test_sha', 'test_msg', 'test_repo') }
  end
end

どちらが呼び出されますが、コミットを参照することMyOtherClass.new("test_sha", "test_msg", "test_repo")を期待MyOtherClassして上書きしているshaため、これでも欠陥があるように見えますが、messageより多くのコードが役立つ可能性があります

于 2014-07-30T19:32:29.347 に答える