Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在自定义策略中使用特征关联_Ruby On Rails_Ruby_Rspec_Factory Bot - Fatal编程技术网

Ruby on rails 在自定义策略中使用特征关联

Ruby on rails 在自定义策略中使用特征关联,ruby-on-rails,ruby,rspec,factory-bot,Ruby On Rails,Ruby,Rspec,Factory Bot,我已经为FactoryGirl建立了一个自定义策略,但不幸的是,传递给这个策略并包含关联的特征处理得很奇怪——如果我为特征a定义了关联,那么它也会为特征B定义关联,即使它没有定义它。下面是一个例子: factory :debtor_steps, class: Debtor do trait :first do association :party end trait :last do association :branch statu

我已经为FactoryGirl建立了一个自定义策略,但不幸的是,传递给这个策略并包含关联的特征处理得很奇怪——如果我为特征a定义了关联,那么它也会为特征B定义关联,即使它没有定义它。下面是一个例子:

factory :debtor_steps, class: Debtor do
    trait :first do
      association :party
    end

    trait :last do
      association :branch
      status_reason_code 1
    end
end
以及一些示例输出:

(byebug) FactoryGirl.build_attributes_for(:debtor_steps)
{:party_id=>nil, :branch_id=>nil}
(byebug) FactoryGirl.build_attributes_for(:debtor_steps, :first)
{:party_id=>2, :branch_id=>nil}
(byebug) FactoryGirl.build_attributes_for(:debtor_steps, :last)
{:status_reason_code=>1, :party_id=>nil, :branch_id=>2}
自定义策略基于
build
构建,基本上提取构建对象的散列(类似于
attributes\u,但使用外键)


正如你所看到的,即使使用的特征没有定义它,关联也是存在的。我如何解决这个问题?

这些关联在您的模型上是真实的吗?在这种情况下-它们确实总是存在,只是设置为nil。是的,它们在我的模型上,但我只想为我在工厂中定义的字段生成属性。因为它们在您的模型中-属性总是存在。无论您是否生成它们。您不应该测试属性是否在模型上定义。。。您应该测试属性是nil还是present。。。在这种情况下,定义与否并不重要,但既然工厂总是假设存在关联,那么为什么您可以在工厂上定义关联呢?FactoryGirl不会自动对您的模型进行反思,以找出存在与否的关联,这就是您必须告诉它的原因。然而,在您的真实模型上,关联总是存在的,因此无论factorygirl是否知道,您的代码都应该能够处理这些关联总是存在的事实。