【问题标题】:FactoryGirl initialize_with multiple paramsFactoryGirl initialize_with 多个参数
【发布时间】:2014-07-30 17:46:19
【问题描述】:

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

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吗?

【问题讨论】:

    标签: ruby-on-rails ruby factory-bot factories


    【解决方案1】:

    上面的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 引用提交并覆盖sha 和message,也许更多代码会有用

    【讨论】:

    • 仅供参考-您可以调用initialize_with { new(attributes) } 来获得相同的效果,使用工厂的所有公共属性。
    【解决方案2】:

    您需要将repo 设为工厂的transient 属性。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多