0

我在 Rails 应用程序中使用 FactoryGirl 进行 RSpec 功能测试。在编写工厂时,我发现需要定义私有方法或宏来删除工厂中的重复代码。宏应该只能从工厂定义中调用。请帮助

factory :subscriber, :class => Subscriber do                                                                                                   
  sequence(:name) { |n| "test_user_#{n}" }                                                                                                     
  sequence(:email) { |n| "test_user_#{n}@example.com"}                                                                                                                   
  association :authentication, factory: :authentication                                                            

  factory :subscriber_with_subscription do                                                                                                     

    ignore do
      payment_pending_subscriptions 0                                                                                                          
      purchased_subscriptions 0
      active_subscriptions 0                                                                                                           
    end                                                                                                                                        

    after(:create) do |subscriber, evaluator|                                                                                                  

      count = evaluator.payment_pending_subscriptions
      FactoryGirl.create_list(:subscription, count, status: 'payment_pending', :subscriber => subscriber) if count >0                         

      count = evaluator.purchased_subscriptions
      FactoryGirl.create_list(:subscription, count, status: 'purchased', :subscriber => subscriber) if count > 0

      count = evaluator.active_subscriptions
      FactoryGirl.create_list(:subscription, count, status: 'active', :subscriber => subscriber) if count > 0
    end
  end
end

如果我可以在工厂内定义一个方法,使得

def create_subs count, status
  FactoryGirl.create_list(:subscription, count, status: status, :subscriber => subscriber) if count > 0
end

然后可以将调用减少到一行/状态

create_subs evaluate.purchased_subscription, "purchased_subscription"

但即使在定义 create_subs 之后,它也会给出错误,即找不到。

4

0 回答 0