Do you struggle with understanding what to test and how to test it?… Maybe you know that “you need to test the behavior of your objects”, but of those behaviors, what do you test?, and how do you test it?… are you looking for some kind of simple steps or methodology to apply? a repeatable process?
In the last years, working on several applications, I have developed a kind of “style” of writing my unit tests, that has helped me to reduce that anxiety of not knowing what to test or if I should test something or not…
So I want to share with you a template that I have extracted from my daily work to help you know what to test when you are creating a record on your App, and you want to write unit tests for it (the examples are in ruby but you can use them almost in every language).
You will be able to apply this template when you are…
you know, that kind of things…
This is the template that I almost always start with…
module Things describe "Create Thing" do it "has a form" do # Tests the form fields and default values. # (Only if you need a form to create the thing) end it "creates a record" do # Tests that the record was created with the right values. end it "returns success" do # Tests that when the thing was created successfully it returns a # success status. end describe "with <bad value>" do # When a bad value is passed it "does not returns success" do # Tests that it does not returns a success status. end it "does not creates the record" do # Tests that it does not creates the record. end it "returns an error" do # Tests that the right error is returned. end end end end
Some times you will need to write more test for more complex behaviors, here is what you can do for some common cases…
You can test them switching the
describe and adding more
describe "has a form" do example "<case 1>" do end example "<case 2>" do end #... end
Also you can test them switching the
describe and adding more
describe "creates a record" do example "<case 1>" do end example "<case 2>" do end #... end
To test them you can add more
describe "with <bad value>" do end describe "with <other bad value>" do end describe "with <other bad value>" do end
I hope that this template can help you visualize better the things that you can test. Some times this template will not be enough but I think and hope it can help you in a lot of cases on your daily work!
I have an email course with with a guide to help you start with TDD!