0

so the issue is that mail is not being added to ActionMailer::Base.deliveries.

FactoryGirl.create is returning nil. what am I doing wrong?

FactoryGirl.define do 
  factory :provisional_user do
    sequence(:email) { |n| "bangbang_#{n}@example.com" }
    first_name "Provisional"
    last_name "User"
    partner "source2"
    unsubscribed false
  end

  factory(:unsubscribed_user, :parent => :provisional_user, :class => ProvisionalUser) do
    sequence(:email) { |n| "do_not_contact@example.com" }
    first_name "Unsubscribed"
    last_name "User"
    partner "source2"
    unsubscribed true
  end


  factory(:subscribed_user, :class => ProvisionalUser) do
    sequence(:email) { |n| "please_contact@example.com" }
    first_name "Subscribed"
    last_name "User"
    partner "source2"
    unsubscribed false
  end
  ...
end

then in my test (i also tried FactoryGirl.create without the save! on the following line):

require "rspec"
require "spec_helper"
require "action_mailer"

describe "unsubscribe functionality" do

  before(:each) do
    ActionMailer::Base.deliveries = []
  end

  it "should send emails to subscribed users only" do
    unsubscribed_user = FactoryGirl.build(:unsubscribed_user)
    unsubscribed_user.save!

    subscribed_user = FactoryGirl.create(:subscribed_user)
    puts "the user is" + subscribed_user.to_s
    CoRegEmailWorker.perform
    #sent.length.should == 1
    sent.first.email.should =~ subscribed_user.email
    sent.first.email.should_not =~ unsubscribed_user.email
  end

  def sent
    ActionMailer::Base.deliveries
  end

end

but it's failing like this:

Failure/Error: sent.first.email.should =~ subscribed_user.email
  NoMethodError:
   undefined method `email' for nil:NilClass
  # ./spec/mailers/provisional_users_notifier_spec.rb:21
Ramy
  • 20,541
  • 41
  • 103
  • 153

2 Answers2

1

In the code you put here, you only have defined unsubscribed_user, but no subscribed_user, so subscribed_user would be nil, and there may be the problem.

mornaner
  • 2,424
  • 2
  • 27
  • 39
  • @Ramy, sorry, i was not so clear there... I meant in the test, you do unsubscribed_user=factory_girl.build(...), but do not define a subscribed user – mornaner Jan 13 '12 at 18:15
  • sorry it was in the upper part of the function, before the "before_each" call. i updated my post. – Ramy Jan 13 '12 at 18:26
0

Does your user class have a one-to-one or one-to-many association? I had a similar error message and solved it by creating my factory object by including the association. This was helpful:

How to create has_and_belongs_to_many associations in Factory girl

Community
  • 1
  • 1
RonanOD
  • 876
  • 1
  • 9
  • 19