A roughly guideline for testing is:
- Test only your API (disclaim testing the private methods)
- Do not test tested code (Ruby, gems or frameworks).
- Write at least 1 test for every public method.
- Assert only 1 expectation of the tested method.
- Specify first, code afterwards
user$ gem install rspecworks.
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 endThe 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 endIn 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.rbSince 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 failureas expected.
After implementing the brand new fancy feature:
class Example def feature "Awesome" end endand running the test, it returns:
Finished in 0.00073 seconds 1 example, 0 failuresGreat!
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
Keine Kommentare:
Kommentar veröffentlichen