FactoryGirl: why does attributes_for omit some attributes?

前端 未结 5 1300
借酒劲吻你
借酒劲吻你 2020-12-03 10:57

I want to use FactoryGirl.attributes_for in controller testing, as in:

it \"raise error creating a new PremiseGroup for this user\" do
  expect {
    post :c         


        
5条回答
  •  暖寄归人
    2020-12-03 11:29

    The accepted answer seems outdated as it did not work for me, after digging through the web & especially this Github issue, I present you:

    A clean version for the most basic functionality for Rails 5+

    This creates :belongs_to associations and adds their id (and type if :polymorphic) to the attributes. It also includes the code through FactoryBot::Syntax::Methods instead of an own module limited to controllers.

    spec/support/factory_bot_macros.rb

    module FactoryBot::Syntax::Methods
      def nested_attributes_for(*args)
        attributes = attributes_for(*args)
        klass = args.first.to_s.camelize.constantize
    
        klass.reflect_on_all_associations(:belongs_to).each do |r|
          association = FactoryBot.create(r.class_name.underscore)
          attributes["#{r.name}_id"] = association.id
          attributes["#{r.name}_type"] = association.class.name if r.options[:polymorphic]
        end
    
        attributes
      end
    end
    

    this is an adapted version of jamesst20 on the github issue - kudos to him

提交回复
热议问题