What is odd about these tests?

Question: What is unusual about this test?

  expect false do
    validation = Validatable::ValidatesLengthOf.new 
                 stub_everything, 
                 :username, :maximum => 8
    validation.valid?(stub(:username=>"usernamefdfd"))
  end

Answer: They are anonymous. Jay Fields has written about why this might be a good idea, and included feedback from a bunch of people who care about this kind of thing.

The example above is from tests in Jay's validatable library. Here is a modified version of the same test:

  account = Struct.new(:name)
  expect false do
    validation = ValidatesLengthOf.new account, 
                 :name, :maximum => 8
    validation.valid?(account.new("this string is too long"))
  end

The modified version changes several things:

  • Rather than a stub, a named struct makes the test look more like a real-world usage.
  • Including Validatable at the top of the module (not shown) keeps namespaces out of the test.
  • Test strings can have values that name their purpose, e.g. "this string is too long".

Much food for thought here. How would you answer these questions?

  • Do you prefer the stub or the struct version? Do anonymous tests change your ideas about when to stub? How?
  • Struct.new is more typical of real-world usage than a stub would be. A named class would be even more typical. Why would using a named class be a bad idea in languages like Ruby and Java, and what features would a language need to fix the problem?
  • Do the string names make the test more readable? Do they re-introduce the problem Jay was solving in the first place?
Get In Touch