I’m just getting into TDD with Rails. Something that is puzzling me is “when to write the tests”. All guides suggest that you should write the tests before writing any code, but if I create a Person model and then write the following test before writing any code;
p = Person.new
p.firstname = "mikey"
p.lastname = "hogarth"
assert_equal p.fullname, "mikey hogarth"
then the test itself will not fail, it will crash! Because I haven’t implemented the “fullname” method yet, I’ll get a runtime error. I therefore can’t possibly make that test fail until I’ve written the code.
How do TDD coders usually approach this sort of situation? Is it basically with dummy method stubs or is there a better way?
===EDIT===
Lots of great ideas suggested. I eventually decided that the following option achieves what I was trying to do most elegantly;
if p.respond_to? "fullname"
assert_equal "Mikey Hogarth", p.fullname
else
flunk "fullname not implemented"
end
===SECOND EDIT===
If you stumble across this answer, it seems my whole approach to TDD was the problem, so while the code above will work it isn’t good practice.
You want to write the code you wish you had. In C style languages/statically compiled languages, the above would not even compile, as you correctly stated the code does not exist. This is fine, you would then implement the bare minimum to make the code build in order to run your tests. In other words, your tests drive your design.
My Ruby is very rusty but in the above example something along the lines of
method_missingwill be thrown for the methods/properties that do not exist. Therefore you would create them.If you run your test now you will get nil returned from fullname. Therefore we would implement the fullname method. The point to note here is that message has changed, rather than Ruby moaning about missing methods, the test is moaning that we have not implemented the methods correctly.
Now your test will pass.
Basically you want to either change the message that your test displays after running (this will prove you are getting somewhere) or you want to make it pass. After the test is passing, you can refactor. The above method is simple, but you could drop the return statement, use string formatting or whatever. As long as the test passes after, you know you’re good to go.