First, create something that works. It doesn't need to be nice or perfect, it should just work (and if possible not introduce big security risks).
Based on that, write tests.
As time passes, slowly fix bugs and beautify the code.
I've (first unconsciously ;) used this for several years now and I think it's a good approach. You quickly get actually working software (which is the most important goal IMHO - there's no sense in perfect software which will never be finished) and gradually make it better. You may have to rewrite it one or two times, but that's actually good since you already have experience then – so you know what you shouldn't do this time etc.