How to learn TDD with Ruby?

五迷三道 提交于 2019-11-29 22:20:41

The best way to learn TDD is by just doing it. I suggest you build a new project using TDD. This means don't write any non-testing code unless you have a failing test.

It will make you think about writing tests: I want to write this code, how do I write a test for it so I can write it.

It will show you the layered nature of testing. Instead of want a name that is required and can't contain numbers. you'll first test setting and reading a name, test requiring the name, test it shouldn't contain numbers, than think if it has more constraints and test those.

Remember:

  • Write a test before you write the code
  • Make sure the test fails! It's important to know you're testing logic is correct
  • Before writing the next test make sure all tests succeed
  • You can always clean up your code, if the tests keep working you didn't change the design

Try RubyKoans.

It's tricky getting your head around TDD (and BDD) but the book RSpec Book - BDD helped me a lot. Behaviour driven development is not exactly the same thing as TDD, but it is close and you have to think in a similar way.

One test at a time. That's the only secret, the rest is just practice, although you'll need to do a lot of practice ;-)

You already have enough to get started: Ruby has the test/unit library, which is quite sufficient to start with.

Try Googling for Ruby test/unit and Ruby TDD. A couple of useful starting points I found are here and here.

I'd start the practice with a completely new project, preferably a sideline one where you're able to progress slower at first. Be really strict - all code should be written as a result of a failing test. Remember the third part of the "red-green-refactor" mantra - you'll soon get into trouble without it (trust me, I've been there).

Once you feel you're starting to become comfortable with the technique (one sign may be that you notice that you don't really have a code-test-debug cycle any more) then start looking at some alternatives: rspec is the main one, but there are others (riot, minitest is the Ruby 1.9 default, if you're on 1.8.x)

I still recommend TDD by Example by Kent Beck. It's an easy read and gives you all the basics.

I personally found the Peepcode RSpec screencast very helpful, they give you a nice idea of what to test plus they get you started with RSpec quickly. It took me a while to get started on TDD, but it's worth it!

I agree with the answers about reading "TDD by Example" by Kent Beck and about having a real project where you force yourself to do it.

You may also find Back to Basics: Writing Unit Tests First useful as a Ruby-related reference.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!