3

我有一个初始化时有多个参数的模型,其中一个用于实例化模型的方法中:

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上面的Commit类的方法,因为这就是你所调用的Commit.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引用提交并正在覆盖shamessage也许更多代码会很有用

于 2014-07-30T19:32:29.347 回答
3

您需要制作工厂repotransient财产。

FactoryGirl.define do
  factory :commit do
    sha "test_sha"
    message "test_message"
    transient { repo "test_repo" }
    intialize_with { new(sha: sha, message: message, repo: repo) }
  end
end
于 2015-05-22T07:08:13.710 回答