Skip to main content

Hooks: Before and After

Knapsack exposes four hooks to execute arbitrary code before or after certain events:

KnapsackPro::Hooks::Queue.before_queue do |queue_id|
puts 'before_queue - run before the test suite'
end

KnapsackPro::Hooks::Queue.before_subset_queue do |queue_id, subset_queue_id|
puts 'before_subset_queue - run before the next subset of tests'
end

KnapsackPro::Hooks::Queue.after_subset_queue do |queue_id, subset_queue_id|
puts 'after_subset_queue - run after the previous subset of tests'
end

KnapsackPro::Hooks::Queue.after_queue do |queue_id|
puts 'after_queue - run after the test suite'
end

RSpec​

Get tests and the status of each batch of tests in RSpec​

The KnapsackPro::Hooks::Queue.before_subset_queue and KnapsackPro::Hooks::Queue.after_subset_queue hooks get a 3rd variable - the queue.

The queue variable stores an enumerable collection with each batch of tests fetched from the Queue API. The batch has:

  • a list of test file paths (KnapsackPro::Batch#test_file_paths returns an array like ['a_spec.rb', 'b_spec.rb'])
  • a status of the given set of tests in the batch (KnapsackPro::Batch#status returns :not_executed, :passed or :failed)

Example usage:

spec_helper.rb
KnapsackPro::Hooks::Queue.before_subset_queue do |queue_id, subset_queue_id, queue|
print "Tests from all batches fetched from the Queue API so far: "
puts queue.map(&:test_file_paths).inspect

queue.each(&:test_file_paths) # you can use each as well

print "Current batch tests: "
puts queue.current_batch.test_file_paths.inspect

print "Current batch status: "
puts queue.current_batch.status # returns :not_executed in the `before_subset_queue` hook
end

KnapsackPro::Hooks::Queue.after_subset_queue do |queue_id, subset_queue_id, queue|
print "Tests from all batches fetched from the Queue API so far: "
puts queue.map(&:test_file_paths).inspect

print "Current batch tests: "
puts queue.current_batch.test_file_paths.inspect

print "Current batch status: "
puts queue.current_batch.status # returns :passed or :failed in the `after_subset_queue` hook
end

percy-capybara​

percy-capybara >= 4​

If you are using percy-capybara >= 4, you need to configure the environment variables as explained in Percy's docs.

After that, you can use the following command:

npx percy exec --parallel -- rake knapsack_pro:queue:rspec
# or with the knapsack_pro binary
npx percy exec --parallel -- knapsack_pro queue:rspec

Here you can find the docs for the knapsack_pro binary.