📜 ⬆️ ⬇️

factory_trace gem will help clean your factories

If you write tests for your project and use factory_bot to generate test data, I present you the factory_trace gem, which will help you keep your factories & traits up to date.

What is he doing?


During the launch of your tests, heme monitors the use of certain factories, and at the end of execution displays the resulting report.

$ FB_TRACE=1 rspec total number of unique used factories & traits: 3 total number of unique unused factories & traits: 2 unused global trait with_email unused factory admin 

Project Integration


For RSpec, it is enough to install gems and you can use, for any other tester, it is enough to do simple manipulations:
')
 #      FactoryTrace.start #     FactoryTrace.stop 

Parallel / piecewise execution


Often, if tests take a long time, they are run in different processes in parts, and in order for the data on unused factories to be correct, it is necessary to process statistics from all tests.

This can be done as follows:

 #   FB_TRACE=trace_only FB_TRACE_FILE=fb_trace_result1.txt bundle exec rspec spec/first_spec.rb #   (    ) FB_TRACE=trace_only FB_TRACE_FILE=fb_trace_result2.txt bundle exec rspec spec/second_spec.rb #     bundle exec factory_trace fb_trace_result1.txt fb_trace_result2.txt 

How it works?


Thanks to implementing factory_bot using ActiveSupports::Notifications it is easy to add a callback when the factory is used:

 ActiveSupport::Notifications.subscribe('factory_bot.run_factory') do |_name, _start, _finish, _id, payload| name = payload[:name] traits = payload[:traits] storage[name] ||= Set.new storage[name] |= traits end 

And after collecting all the information, we find unused factories with a simple algorithm.

post scriptum


Try it yourself and share your feedback, I will be grateful!

Thanks for attention.

Source: https://habr.com/ru/post/450758/


All Articles