Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FactoryGirl initialize_with multiple params

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?

like image 557
bryce Avatar asked Apr 27 '26 16:04

bryce


2 Answers

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

like image 170
engineersmnky Avatar answered Apr 30 '26 06:04

engineersmnky


You need to make repo a transient property of the factory.

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
like image 20
Dave Sag Avatar answered Apr 30 '26 06:04

Dave Sag