Reputation: 2355
I'm building a test suite to teach OOP. I want the files in my spec/lib
folder to be executed in a specific order.
I would like to define an array of class names, and their test suite would be executed in order. For example:
spec_order = %w(
FirstClass
SecondClass
ThirdClass
)
How might I accomplish this?
Upvotes: 9
Views: 7815
Reputation: 3761
Of course it's good practice to have randomization by default, but in some cases, such as when trying to track down order-related issues in your specs, or for documentation generation, it might be nice to specify a temporary order.
You can specify a "global" ordering for some (or all) of your spec files as follows:
config.register_ordering(:global) do |items|
files = <<END.split("\n")
./spec/some_spec.rb
./spec/another_spec.rb
END
# Original RSpec random order
randomized = RSpec::Core::Ordering::Random.new(config).order(items)
# Now do a stable sort by filename index
randomized.sort_by.with_index do |example_group, index|
files.index(example_group.file_path) || files.size + index
end
end
Documentation for register_ordering
is available on Relish.
Upvotes: 1
Reputation: 2355
Name the _spec.rb
files numerically:
01_first_spec.rb
02_second_spec.rb
...
Create a .rspec
file
# .rspec
--order defined
Now, when running rspec
the files should be executed in sorted order.
Upvotes: 11
Reputation: 5049
Ordering tests is not recommended by almost all testing frameworks. That is part of making sure that tests are independent and don't yield unexpected behavior when order changes.
However, if you want to run test files in specific order then you can accomplish that by writing scripts:
Consider the following script (ordered_test_script.sh):
for f in file1_spec.rb file2_spec.rb file3_spec.rb
do
rspec $f
done
Make sure the script is executable:
chmod +x ordered_test_script.sh
Then you can run the script:
./ordered_test_script.sh
First, you might want to extend the String class to include an underscore method:
class String
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
This will turn camelcase class names to underscore ones. For example (MyClass => my_class)
classes = %w(MyClass1 MyClass2 MyClass3)
classes.each do |c|
system("rspec #{c.to_s.underscore}_spec.rb")
end
Hope this helps.
Upvotes: 2