thoughtbot / thoughtbot/factory_bot
Add find_or_create_by Method
Open
Nobody has claimed this yet.
feature
- Dominant language
- Ruby
- Stars
- 8.2k
- Forks
- 2.6k
- PR merge metrics
- No merged PRs in 30d
Description
Problem this feature will solve
When setting up test data with FactoryBot, it can be cumbersome and repetitive to check if a record exists before creating it.
For instance, in our current test setup, we have to manually use find_by followed by create if the record is not found.
RSpec.describe User do
before(:all) { Fixtures.setup_basics }
it do
# aa
end
it do
# aa
end
end
module Fixtures
def self.setup_basics
setup_normal_plan
setup_high_plan
end
def self.normal_plan
a_token = FactoryBot.create(:token :free)
b_token = FactoryBot.create(:token, :normal)
# etc...
end
def self.high_plan
a_token = Token.find_by(name: "free") || FactoryBot.create(:token :free)
b_token = Token.find_by(name: "normal") || FactoryBot.create(:token :normal)
end
end
Desired solution
def self.high_plan
a_token = Token.find_or_create_by(:token :free)
b_token = Token.find_or_create_by(:token :normal)
end
Alternatives considered
def self.high_plan
a_token = Token.find_by(name: "free") || FactoryBot.create(:token :free)
b_token = Token.find_by(name: "normal") || FactoryBot.create(:token :normal)
end
Additional context
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reviewing the existing FactoryBot find_by and create entry points and how they are tested. Clarify the intended argument and lookup behavior for find_or_create_by, then confirm completion with tests covering both finding an existing record and creating a missing one.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- ruby
- Domain
- testing
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100