Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run rspec with no observers in rails 3?

I have a rails3 app that has some observers. I can't for the life of me figure out how to turn these off for my rspec tests!

like image 694
phil Avatar asked Oct 18 '10 17:10

phil


2 Answers

no_peeping_toms will output deprecation warnings when used with Rails 3.1+. It currently has 7 pull requests open to remove these deprecation warnings, however the gem is not necessary with Rails 3.1+. Rails 3.1 added to ActiveModel (and therefore ActiveRecord) the ability to enable and disable observers.

You can put the following line in spec_helper to turn off all observers on all ActiveRecord-descendant models:

# spec/spec_helper.rb
...
RSpec.configure do |config|
  ...
  config.before do
    ...
    ActiveRecord::Base.observers.disable :all # <-- Turn 'em all off!
  end
end

You can turn them back on selectively to test their behavior by wrapping actions in your specs with the enable method.

# spec/models/foo_observer_spec.rb
describe FooObserver do
  subject { FooObserver.instance }

  it 'notices when new Foos are created' do
    subject.should_receive(:after_create)

    Foo.observers.enable :foo_observer do # <- Turn FooObserver on
      Foo.create('my new foo')
    end                                   # <- ... and then back off
  end
end
like image 74
Robb Kidd Avatar answered Nov 01 '22 15:11

Robb Kidd


Two options might be:

  1. No peeping toms
  2. Add the following to your test.rb environment: config.active_record.observers = []
like image 41
astjohn Avatar answered Nov 01 '22 15:11

astjohn