Silencing Deprecation Warnings in Rspec
Published 11 January 11 by Justin French
If you’re testing the behavior of deprecated code in your Ruby project, the warning messages littered throughout your spec output is incredibly noisy.
You could silence all warnings with ::ActiveSupport::Deprecation.silenced = true, but you might miss out on an important warning in one of your dependencies. It’s tempting to remove the tests altogether (the code will be burned soon too, right?), but I figured out something a little nicer a little while back in Formtastic’s test suite.
Throw this code in spec/support/deprecations.rb:
def with_deprecation_silenced(&block)
previous_setting = ::ActiveSupport::Deprecation.silenced
::ActiveSupport::Deprecation.silenced = true
yield
::ActiveSupport::Deprecation.silenced = previous_setting
end
You can then wrap that block around almost any part of your test suite to temporarily turn off the deprecation warnings. Here’s an example:
describe '#bah' do
with_deprecation_silenced do
it 'should be deprecated' do
::ActiveSupport::Deprecation.should_receive(:warn).any_number_of_times
Foo.new.bah
end
it 'should return true' do
Foo.new.bah.should be_true
end
end
end
Better still, I recently discovered that ActiveSupport already has method for this, but it’s currently hidden in the Rails documentation (it’ll be fixed in next stable release). So I can change my code to something like this:
def with_deprecation_silenced(&block)
::ActiveSupport::Deprecation.silence do
yield
end
end
Alternatively, we could just use the ActiveSupport method directly in our tests:
describe '#bah' do
::ActiveSupport::Deprecation.silence do
it 'should be deprecated' do
::ActiveSupport::Deprecation.should_receive(:warn).any_number_of_times
Foo.new.bah
end
it 'should return true' do
Foo.new.bah.should be_true
end
end
end
The (lesser) alternative would be to roll your own in RSpec’s before and after blocks:
describe '#bah' do
before do
@old_silence_config = ::ActiveSupport::Deprecation.silenced
::ActiveSupport::Deprecation.silenced = true
end
#...
after do
::ActiveSupport::Deprecation.silenced = @old_silence_config
end
end
This is one of the many simple reasons why I love Ruby’s blocks!
Before you go…
Here’s some links to my most popular posts: