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?

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

class MyModuleTest
  include MyModule

it 'should be something' do be_something

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{ include MyModule }

it 'should do something' do be_something

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




Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s