Sonntag, 4. Mai 2014

Do it RSpec!

Needless to say that testing code is essential for beeing successful. When it comes to Ruby, there are a lot of helping test frameworks out there with different flaviours. In any case tests should imply specifications. On the basis of that awareness specifying first means writing tests first.
A roughly guideline for testing is:
  1. Test only your API (disclaim testing the private methods)
  2. Do not test tested code (Ruby, gems or frameworks).
  3. Write at least 1 test for every public method.
  4. Assert only 1 expectation of the tested method.
  5. Specify first, code afterwards
Installing the RSpec gem:
user$ gem install rspec
works.
Doing it the TDD way, the new feature method has to be described/ specified first. A convention is to name the spec file class-to-be-tested_spec.rb. In this example it is the example_spec.rb:
# example_spec.rb
require "./example.rb"
describe Example do
  it "should have a new awesome feature" do
    example = Example.new
    example.feature.should eq("Awesome")
  end
end
The Ruby file for testing (example.rb) has to be required on top of the test file as shown above. All tests of a class should be wrapped in a description, calling the RSpec describe. Aside the uninspired naming of the class (Example) it specifies the test in a humanized and readable manner and of course it tests the feature. The test itself is wrapped in a skeleton:
it "should describe your specification in a descriptive manner" do
  # assumption what your method should return according to your specification
end
In real life, methods may be a little bit more complex and therefore more than only one test could be reasonable.
Runing the test:
user$ rspec example_spec.rb
Since the feature was not implemented, the Example class returns:
Failures:

  1) Example should return feature
     Failure/Error: example.feature.should eq("Awesome")
       
       expected: "Awesome"
            got: nil
       
Finished in 0.00827 seconds
1 example, 1 failure
as expected.
After implementing the brand new fancy feature:
class Example
  def feature
    "Awesome"
  end
end
and running the test, it returns:
Finished in 0.00073 seconds
1 example, 0 failures
Great!
The more tests you will write using RSpec, the more you will get familiar with it. The A great resource for further reading is the documentation of RSpec itself.

Supported by Ruby 1.9.3 and RSpec 2.12.0