Search code examples
ruby-on-railsrspecrspec-railsdatabase-cleaner

Passing argument to a rspec test example


I have some tests that are using a big, test database. I'm also using Database Cleaner to clean the database after each tests. And here comes the problem. In my spec helper I have this

config.around(:each) do |example|
  MongoLib.new(database: "#{Rails.env}_sensor_data").drop_tables!
  DatabaseCleaner.cleaning do
    example.run
  end
end

But, here's the problem. The mentioned group of tests (a big group), generates and drops this big database over and over again (once for each test). That takes a long time, and those tests does not change the database at all, so I don't really want to clean and create the database every time.

So, is there a way to do something like this:

it 'something', argument do
  #testing
end

So in the spec helper I can do something like this:

config.around(:each) do |example|
MongoLib.new(database: "#{Rails.env}_sensor_data").drop_tables!
  if example.argument?
    DatabaseCleaner.cleaning do
      example.run
    end
  end
end

Or maybe there is other solution for that problem? Any ideas?


Solution

  • You've got the right idea. Each example object in your around hook has the metadata method that returns a hash. So you can tag the tests you want to run the cleaner on, and look for that tag in your hook. Something like this:

    it "does something", :db_clean do
      # ...
    end
    
    config.around(:each) do |example|
      if example.metadata[:db_clean]
        # ...
      else
        # ...
      end
    end
    

    You can learn more about these filters here.