11
votes

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?

1
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.neo
So I would need to write the test in registrations_controller_spec.rb ?country_dev
That's it, as long as the email is being sent from thereneo

1 Answers

9
votes

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.