0

I know that seeding test database is a kind of bad idea. I need to test Stripe api communication in my model tests. I know that external requests in Unit tests is a bad idea too, but nevertheless.

The stripe account has static subscription plan names. So when I test functionality linked with Stripe I need to take them from my database. I use Factory girl gem as a fixture source, but since I need only particular names for Stripe plans I hardcoded them to the factory:

  factory :subscription_type do
    name "Personal"
    frequency "month"
    stripe_plan_id "personal"
  end

Other factories that uses this one is trying to create each time new object with the same field values and due to validation of uniqueness on the subscription_type model, the factories throw errors. I would prefer if they all use the same record (if exists) if called in one example.

What is the best practice here, guys?

Community
  • 1
  • 1
Roaring Stones
  • 1,054
  • 7
  • 22

2 Answers2

0

Why not use sequence(:unique_field) {|n| "unique_field #{n}"}, this will make a variable n with order, then field would be unique.

dddd1919
  • 868
  • 5
  • 13
0

If you'd like to have only one subscription_type object, try creating it first, and passing it as a parameter for the other factories:

@subscription_type = FactoryGirl.create :subscription_type

@other_object = FactoryGirl.create :other_object, subscription_type: @subscription_type

You could also try to define a smart relation for your factory where it checks if there is a subscription type before:

FactoryGirl.define do 
    factory :user do
      subscription_type { SubscriptionType.first.present? ? SubscriptionType.first : FactoryGirl.create(:subscription_type) }
    end
end
Marcelo Ribeiro
  • 1,718
  • 1
  • 13
  • 27
  • Yeah, that will solve the problem, but the price is little bit high: you have to care about uniqueness of @subscription_type through tests yourself. I was hoping of factory-level solution – Roaring Stones Sep 19 '14 at 02:38
  • Yeah, that is simple and seems to be a solve. Silly me, thanks will tryout. – Roaring Stones Sep 19 '14 at 02:53