Decouple model tests from observers
It is an old news but you really should decouple your model tests from observers. Say, you have an observer that does something not closely related with what the model does, like sending an email notification:
class UserObserver < ActiveRecord::Observer
def after_create(user)
Emailer.someone_signed_up(user).deliver
end
end
A spec like this would trigger the observer each time:
describe User do
it "should create user with valid attributes" do
user = User.new(email: 'user@me.com', name: 'user')
user.save.should be_true
end
end
This will fail if the emailer method fails. You don't want this. Luckily, there is a great gem to the rescue (with somewhat weird name): https://github.com/patmaddox/no-peeping-toms.
Now, put this to Rspec.configure block, and you're done:
ActiveRecord::Observer.disable_observers
What if you really need to have this observer on?
it "should notify founders when someone signs up" do
ActiveRecord::Observer.with_observers(:user_observer) do
User.create(email: 'user@me.com', name: 'user')
ActionMailer::Base.deliveries.should_not be_empty
end
end
Written by Alexey Kuleshov
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#