Skip to content

Commit

Permalink
Merge pull request #94 from sean-dickinson/add-unique-to-fake
Browse files Browse the repository at this point in the history
Feat: Add unique option to fake
  • Loading branch information
flash-gordon authored Jan 21, 2025
2 parents 1406651 + 0c34dd8 commit 3a8155c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
8 changes: 8 additions & 0 deletions docsite/source/index.html.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,14 @@ Factory.define(:user) do |f|
end
```

##### Unique values with fake
Passing the unique: true option will use Faker's [unique](https://github.com/faker-ruby/faker#ensuring-unique-values) feature
```ruby
Factory.define(:user) do |f|
f.email { fake(:internet, :email, unique: true) }
end
```

#### Dependent attributes

Attributes can be based on the values of other attributes:
Expand Down
18 changes: 14 additions & 4 deletions lib/rom/factory/dsl.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,23 @@ module Factory
class << self
# @api private
def fake(*args, **options)
api = fetch_or_store(:faker, *args) do
const, method_name = fetch_or_store(:faker, *args) do
*ns, method_name = args

const = ns.reduce(::Faker) do |obj, name|
obj.const_get(::Dry::Core::Inflector.camelize(name))
end

const.method(method_name)
[const, method_name]
end

api.(**options)
is_unique = options.delete(:unique) { false }

if is_unique
const.unique.public_send(method_name, **options)
else
const.method(method_name).(**options)
end
end
end

Expand Down Expand Up @@ -113,9 +119,13 @@ def timestamps
# @example
# f.email { fake(:number, :between, from: 10, to: 100) }
#
# @example
# f.email { fake(:internet, :email, unique: true) }
#
# @param [Symbol] genre The faker API identifier ie. :internet, :product etc.
# @param [Symbol] type The value type to generate
# @param [Hash] options Additional arguments
# @param [Hash] options Additional arguments, including unique: true will generate unique values
#
#
# @overload fake(genre, subgenre, type, **options)
# @example
Expand Down
12 changes: 12 additions & 0 deletions spec/integration/rom/factory_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,18 @@ class Admin < ROM::Struct
expect(user.created_at).to_not be(nil)
expect(user.created_at).to_not be(nil)
end

it "uses unique when the unique option is true" do
factories.define(:user) do |f|
f.first_name { fake(:name) }
f.last_name { fake(:name, :last_name) }
f.email { fake(:internet, :email, unique: true) }
f.timestamps
end

emails = 10.times.map { factories.structs[:user].email }
expect(emails.uniq.length).to eq(emails.length)
end
end

context "custom non integer sequence primary_key" do
Expand Down

0 comments on commit 3a8155c

Please sign in to comment.