This isn’t something I do all the time, but it’s handy when I’m having writer’s block. It’s a related tactic to “coding by dreaming” - imagine the ideal API, then make it real.

What do you do when you don’t know how to write your test? Instead of getting bogged down in the setup, the public API design, and all the other details… Start with the assertion and work your way up!

This is also a core Behavior Driven Development concept. Focusing on the behavior of the system by starting with the end result just strengths it.

Example

Imagine you’re trying to verify some really complicated behavior. You start with what amounts to an empty screen:

def test_something_really_complicated
end

What do you do first? Well, you could start looking around your system for all the bits and bobs you need. Then you could call a method and see if it does what you expect.

But what if you don’t even really know all those things and you just need a dopamine hit? Getting anything on the page can be a huge success, amiright?

What if we start with something we want to be true?

def test_something_really_complicated
  assert it_works
end

Ok … well, maybe that’s not much progress, but it’s something! How do we know it works?

def test_something_really_complicated
  it_works = system.make_widget.successful?
  assert it_works
end

Oh… well that’s not so bad, right? Maybe those methods don’t exist. Could they? Imagine a world where they did - what would that take?

Let’s finish the current example, though.

def test_something_really_complicated
  system = MySystem.new(dependency_1, dependency_2)
  it_works = system.make_widget.successful?
  assert it_works
end

And just like that, you have a test! It may not be perfect and it may not be fully correct, but you’ve got something on the page. You’ve got a starting point. And, hopefully, you’ve got some more confidence that you can do this.