Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking down your RSpec tests

Some of my Rspec tests have gotten really really big (2000-5000 lines). I am just wondering if anyone has ever tried breaking these tests down into multiple files that meet the following conditions:

  • There is a systematic way of naming and placing your test (e.g. methods A-L gos to user_spec1.rb).
  • You can run a single file that will actually run the other tests inside other files.
  • You can still run a specific context within a file
  • and, good to have, RubyMine can run a specific test (and all tests) just fine.

For now, I have been successful in doing

#user_spec.rb
require 'spec_helper'
require File.expand_path("../user_spec1.rb", __FILE__)
include UserSpec

#user_spec1.rb
module UserSpec do
  describe User do
    ..
  end
end
like image 792
denniss Avatar asked Dec 16 '11 22:12

denniss


1 Answers

If your specs are getting too big, it's likely that your model is too big as well -- since you used "UserSpec" here, you could say your user class is a "God class". That is, it does too much.

So, I would break this up into much smaller classes, each of which have one single responsibility. Then, test these classes in isolation.

What you may find is that your User class knows how to execute most logic in your system -- this is an easy trap to fall into, but can be avoided if you put your logic in a class that takes a user as an argument... Also if you steadfastly follow the law of demeter (where your user class could only touch 1 level below it, but not two).

Further Reading: http://blog.rubybestpractices.com/posts/gregory/055-issue-23-solid-design.html

like image 125
Jesse Wolgamott Avatar answered Sep 28 '22 08:09

Jesse Wolgamott