Skip to content

Commit

Permalink
Handle gracefully fixtures that only exist for tests in `TestHelper.u…
Browse files Browse the repository at this point in the history
…nload_fixture` (#72)

TestHelper.unload_fixture: handle models without data
  • Loading branch information
serioushaircut authored Feb 19, 2024
1 parent 4ca60e5 commit 513d757
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 4 deletions.
22 changes: 18 additions & 4 deletions lib/frozen_record/test_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def load_fixture(model_class, alternate_base_path)

return if @cache.key?(model_class)

@cache[model_class] ||= model_class.base_path
@cache[model_class] = base_path_if_file_present(model_class)

model_class.base_path = alternate_base_path
model_class.load_records(force: true)
Expand All @@ -26,9 +26,10 @@ def unload_fixture(model_class)
return unless @cache.key?(model_class)

old_base_path = @cache[model_class]
model_class.base_path = old_base_path
model_class.load_records(force: true)

if old_base_path
model_class.base_path = old_base_path
model_class.load_records(force: true)
end
@cache.delete(model_class)
end

Expand All @@ -40,6 +41,19 @@ def unload_fixtures

private

# Checks for the existence of the file for the frozen_record in the default directory.
# Returns the base_path if the file is present, otherwise nil.
# Some tests define specific test classes that do ONLY exist in the alternate directory.
# As `unload_fixture(s)` tries to force load the default file, it would raise an error for
# the "test only" fixtures. The nil value in the cache handles that case gracefully.
def base_path_if_file_present(model_class)
if File.exist?(model_class.file_path)
model_class.base_path
else
nil
end
end

def ensure_model_class_is_frozenrecord(model_class)
unless model_class < FrozenRecord::Base
raise ArgumentError, "Model class (#{model_class}) does not inherit from #{FrozenRecord::Base}"
Expand Down
3 changes: 3 additions & 0 deletions spec/fixtures/test_helper/only_in_tests.yml.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
---
- id: 1
name: Some continent
12 changes: 12 additions & 0 deletions spec/test_helper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@
expect(Continent.count).to be == 1
expect(Country.count).to be == 3
end

context "when the test fixture does not exist in normal base path" do
class OnlyInTest < FrozenRecord::Base; end
before do
test_fixtures_base_path = File.join(File.dirname(__FILE__), 'fixtures', 'test_helper')
FrozenRecord::TestHelper.load_fixture(OnlyInTest, test_fixtures_base_path)
end
it 'unload fixture gracefully recovers from an ' do

expect { FrozenRecord::TestHelper.unload_fixture(OnlyInTest) }.not_to raise_error
end
end
end

describe '.unload_fixtures' do
Expand Down

0 comments on commit 513d757

Please sign in to comment.