FactoryGirl initialize_with multiple params

bryce picture bryce · Jul 30, 2014 · Viewed 7.1k times · Source

I have a model with multiple params in initialize, one of which is used in a method on the model on instantiation:

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

And I'm trying to create a factory that initializes it using these params, but am getting wrong number of arguments errors when trying to do:

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

But this gives me wrong number of arguments (0 for 3). Is it not possible to pass multiple args into initialize_with?

Answer

engineersmnky picture engineersmnky · Jul 30, 2014

Is the initialize method above for the Commit class becuase that is what you are calling Commit.new("test_sha", "test_msg", "test_repo")

Since I doubt that's the case this will work for Commit.

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

This will call

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

You will then have to initialize your other object correctly something like

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

Which will call MyOtherClass.new("test_sha", "test_msg", "test_repo") Although even this seems flawed since you are expecting MyOtherClass to reference a commit and are overwriting sha and message maybe more code would be useful