如何在FactoryGirl中实现这个after_create?

时间:2016-02-05 10:28:13

标签: ruby-on-rails ruby-on-rails-4 rspec factory-bot rspec-rails

我有两个模型 - MembershipConnection

在我的Membership模型上,我有after_create回调:

after_create :setup_connection, unless: Proc.new { self.connection_exists }

  def connection_exists
    Connection.where("invited_user_id = :user_a_id AND inviter_user_id = :user_b_id OR invited_user_id = :user_b_id AND inviter_user_id = :user_a_id", user_a_id: self.inviter.try(:id), user_b_id: self.invited.try(:id)).exists?
  end

  def setup_connection
    self.create_inviter_connection!(times_sent: 0, request_status: 0, inviter_user: self.inviter)
  end

这是我的会员工厂,我尝试实施after_create

FactoryGirl.define do
  factory :membership do
    family_tree
    association :inviter, factory: :user
    association :invited, factory: :user
    relation { Faker::Lorem.word }
    member

    after(:create) do |membership, evaluator|
      unless membership.connection_exists
        create(:connection, times_sent: 0, request_status: 0)
      end
    end
  end
end

但这只是导致我的所有测试都失败了。我不确定它是否有效,因为我无法正确测试它。它也需要FORYVER。

这是我的连接工厂:

FactoryGirl.define do
  factory :connection do
    association :invited_membership, factory: :membership
    association :inviter_membership, factory: :membership
    association :invited_user, factory: :user
    association :inviter_user, factory: :user
    sent_at { Faker::Time.backward(7, :evening) }
    responded_at { Faker::Time.forward(21, :morning) }
    send_limit 5
    times_sent 1
    removed_at { Time.now }
  end
end

没有after_create,这是我在此文件中的测试套件的摘要:

Finished in 2.85 seconds (files took 4.88 seconds to load)
21 examples, 0 failures, 1 pending

这是仅添加了after_create的摘要:

Finished in 3 minutes 29 seconds (files took 5.16 seconds to load)
21 examples, 20 failures, 1 pending

很明显,这对我需要的东西不起作用。

关于如何更好地实现这一点的想法?

0 个答案:

没有答案