factory_trace gem helps clean your factories

    If you write tests for your project and use factory_bot to generate test data, I present to 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, the gem monitors the use of certain factories, and at the end of execution it displays a result 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 the gem and you can use it, for any other tester, it is enough to do simple manipulations:

    # добавить до начала исполнения тестов
    FactoryTrace.start
    # добавить после завершения тестов
    FactoryTrace.stop
    

    Parallel / piece 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 the implementation of factory_bot using ActiveSupports::Notificationsit 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.

    Also popular now: