Skip to content

Commit

Permalink
Support file_fixture in Factory definitions
Browse files Browse the repository at this point in the history
Related to [factory_bot#1282][]

[rails/rails#45606][] has been merged and is likely to be released as
part of Rails 7.1.

With that addition, the path toward resolving [factory_bot#1282][]
becomes more clear. If factories can pass along [Pathname][] instances
to attachment attributes, Active Support will handle the rest.

Instances of `ActiveSupport::TestCase` provide a [file_fixture][] helper
to construct a `Pathname` instance based on the path defined by
`ActiveSupport::TestCase.file_fixture_path` (relative to the Rails root
directory).

[factory_bot#1282]: thoughtbot/factory_bot#1282 (comment)
[rails/rails#45606]: rails/rails#45606
[Pathname]: https://docs.ruby-lang.org/en/master/Pathname.html
[file_fixture]: https://api.rubyonrails.org/classes/ActiveSupport/Testing/FileFixtures.html#method-i-file_fixture
  • Loading branch information
seanpdoyle committed Sep 25, 2023
1 parent 659d74a commit 8a739aa
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/factory_bot_rails/railtie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
require "factory_bot_rails/reloader"
require "factory_bot_rails/factory_validator"
require "rails"
require "active_support/testing/file_fixtures"

module FactoryBotRails
class Railtie < Rails::Railtie
Expand All @@ -31,6 +32,22 @@ class Railtie < Rails::Railtie
end
end

config.after_initialize do
FactoryBot::SyntaxRunner.include ActiveSupport::Testing::FileFixtures

ActiveSupport.on_load :active_support_test_case do
FactoryBot::SyntaxRunner.file_fixture_path = file_fixture_path
end

if defined?(RSpec)
RSpec.configure do |config|
if config.respond_to?(:file_fixture_path)
FactoryBot::SyntaxRunner.file_fixture_path = config.file_fixture_path
end
end
end
end

config.after_initialize do |app|
FactoryBot.find_definitions
Reloader.new(app).run
Expand Down
19 changes: 19 additions & 0 deletions spec/factory_bot_rails/factory_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# frozen_string_literal: true

describe "factory extensions" do
describe "#file_fixture" do
it "delegates to the test harness" do
define_model "Upload", filename: :string

FactoryBot.define do
factory :upload do
filename { file_fixture("file.txt") }
end
end

upload = FactoryBot.build(:upload)

expect(upload.filename).to eq(file_fixture("file.txt").to_s)
end
end
end
Empty file added spec/fixtures/files/file.txt
Empty file.

0 comments on commit 8a739aa

Please sign in to comment.