trouble building with factory girl

我怕爱的太早我们不能终老 提交于 2020-02-07 05:28:22

问题


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

回答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.




回答2:


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



来源:https://stackoverflow.com/questions/8854517/trouble-building-with-factory-girl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!