Ruby : Rspec : Keep Specs Fresh With Anonymous Classes

Keep Specs Fresh With Anonymous Classes (Copied)

Sometimes it can be difficult to test a module since you don’t want to test it tied to a specific implementation. Let’s say we have a module that looks like this:

module MyModule
  def something?
    true 
  end
end

How can we test it? One solution is to create a “test” class like this:

class MyModuleTest
  include MyModule
end

it 'should be something' do
  MyModuleTest.new.should be_something
end

But there’s a problem with that approach: since your test class lives outside the scope of your test, it doesn’t get torn down at the end of each test run without manual intervention. So what can we do instead?

let(:fresh_class) do
  Class.new{ include MyModule }
end

it 'should do something' do
  fresh_class.new.should be_something
end

Now we get a pristine class each and every test that we know doesn’t have any state baggage. Anonymous classes to the rescue!

 

Sources:

http://www.intridea.com/blog/2012/2/13/using-anonymous-classes-and-modules-in-ruby

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s