RSpec testing Devise Mailer
Asked Answered
H

1

12

I am new to RSpec and TDD and I am having difficulties writing a RSpec test to test if Devise is actually sending the confirmation email after a user signs up. I know that my application is working as expected because I have physically tested the functionality in both development and production. However, I am still required to write the RSpec test for this functionality and I cannot figure out how to send a confirmation email through RSpec tests.

factories/user.rb

FactoryGirl.define do
  factory :user do
    name "Jack Sparrow"
    email { Faker::Internet.email }
    password "helloworld"
    password_confirmation "helloworld"
    confirmed_at Time.now
  end
end

spec/models/user_spec.rb

require 'rails_helper'

RSpec.describe User, type: :model do

  describe "user sign up" do
    before do
      @user = FactoryGirl.create(:user)
    end

    it "should save a user" do
      expect(@user).to be_valid
    end

    it "should send the user an email" do
      expect(ActionMailer::Base.deliveries.count).to eq 1
    end
  end
end

Why is Devise not sending a confirmation email after I create @user? My test returns ActionMailer::Base.deliveries.count = 0. As I said, I am new to RSpec and TDD so am I completely missing something here?

Hindsight answered 16/6, 2015 at 19:10 Comment(3)
I'm guessing the email is being sent on the controller create action, here you're just creating a new user and expecting it send an email. So I would write a test for the controller create action and do a post with some user attributes, mailer should be invoked.Wintertime
So I would need to write the test in registrations_controller_spec.rb ?Hindsight
That's it, as long as the email is being sent from thereWintertime
C
11

Devise uses its own mailer, so try Devise.mailer.deliveries instead of ActionMailer::Base.deliveries if putting the test in the right controller's file doesn't work by itself.

Cutoff answered 10/8, 2015 at 17:36 Comment(1)
expect(Devise.mailer.deliveries.count).to eq 1 worked for me, thank you!Soapbark

© 2022 - 2024 — McMap. All rights reserved.