Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails RSpec Testing: Undefined method 'deliver' for nil:NilClass

I"m trying to test whether a method triggers an email in my Rails 3.2 using RSpec. It works in production and development, I just can't get it to pass my test.

I'm getting the error undefined method 'deliver' for nil:NilClass

# user_spec.rb
it "should send an email if user has weekly email set to true" do
  @user = FactoryGirl.create(:user, user_name: "Jane Doe", email: "[email protected]", weekly_email: true, weekly_article_count: 10)
  Mailer.should_receive(:weekly_email)
  User.send_weekly_email
end

# user.rb
scope :weekly_email, where(:weekly_email => true)
scope :weekly_article_count, :conditions => ["weekly_article_count IS NOT NULL"]

def self.send_weekly_email
  @users = User.weekly_email.weekly_article_count
  @users.each do |user|
    Mailer.weekly_email(user).deliver
  end
end

I've also tried using Mailer.should_receive(:weekly_email).with(user), but then I receive the error undefined local variable or method 'user'

like image 353
yellowreign Avatar asked Jul 31 '13 01:07

yellowreign


2 Answers

Funny, I just had to do this a couple of hours ago. You need to stub out the deliver method as well to stop it from freaking out. Otherwise your should_receive returns nil so when your method calls deliver it's calling nil.deliver.

This should work:

Mailer.should_receive(:weekly_email).and_return( double("Mailer", :deliver => true) )
like image 124
Philip Hallstrom Avatar answered Oct 12 '22 23:10

Philip Hallstrom


Rspec has and_call_original if you don't need to change the original behavior. (doc) In your case, you can use Mailer.should_receive(:weekly_email).and_call_original.

like image 31
Diana Liu Avatar answered Oct 13 '22 00:10

Diana Liu