Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set order of RSpec tests

Tags:

ruby

rspec

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?

like image 922
Richard Avatar asked Sep 23 '15 00:09

Richard


2 Answers

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.

like image 192
Richard Avatar answered Nov 04 '22 16:11

Richard


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:

1. Shell Script

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

2. Ruby Script

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.

like image 2
moeabdol Avatar answered Nov 04 '22 15:11

moeabdol