What is odd about these tests? - No Fluff Just Stuff

What is odd about these tests?

Posted by: Justin Gehtland on June 1, 2008

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?
Justin Gehtland

About Justin Gehtland

Justin is the co-founder of Relevance, a consulting/training/research organization located in the Research Triangle of North Carolina. Justin has been developing applications with static and dynamic languages since 1992. He has written code with Java, .NET, C#, Visual Basic, Perl, Python and Ruby. He loves to talk, especially in front of people, but all by himself in the corner if he must. Justin is currently focused on: Rails (because its the law), Spring (because Java isn't going anywhere) and security (because paranoia is your friend).

Why Attend the NFJS Tour?

  • » Cutting-Edge Technologies
  • » Agile Practices
  • » Peer Exchange

Current Topics:

  • Languages on the JVM: Scala, Groovy, Clojure
  • Enterprise Java
  • Core Java, Java 8
  • Agility
  • Testing: Geb, Spock, Easyb
  • REST
  • NoSQL: MongoDB, Cassandra
  • Hadoop
  • Spring 4
  • Cloud
  • Automation Tools: Gradle, Git, Jenkins, Sonar
  • HTML5, CSS3, AngularJS, jQuery, Usability
  • Mobile Apps - iPhone and Android
  • More...
Learn More »