本文介绍了具有特质的FactoryGirl工厂可返回带有字符串键的哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用FactoryGirl来构建返回如下内容的Hash:

I'm trying to use FactoryGirl to build a Hash that returns something like this:

 => {"3"=>"1", "6"=>"Word"}

我已经接近了,但还没有100%...

I'm getting close but not 100% there yet...

我尝试的第一个工厂定义如下:

The first factory definition i tried looked like this:

factory :faqtory, class: Hash do |f|
  f.ignore do
    fake_word Faker::Lorem.word
  end

  f.sequence(1.to_s) { |n| n }
  f.send(2.to_s,  fake_word.to_s.capitalize)

  initialize_with { attributes.stringify_keys }
end

不幸的是,这不起作用:

Unfortunately this doesn't work:

1.9.3p448 :001 > FactoryGirl.build :faqtory
ArgumentError: Trait not registered: fake_word

在那之后不起作用了,我认为对fake_word的调用需要放在一个块中,但这没什么区别.

After that didn't work i assumed the call to fake_word needed to be in a block but that makes no difference.

有什么建议吗?

推荐答案

忽略的属性定义为可以从其他属性中使用的方法.引用它们时,您需要使用一个块来定义依赖属性:

Ignored attributes are defined as methods that you can use from other attributes. When referring to them, you need to define the dependent attributes using a block:

factory :faqtory, class: Hash do |f|
  f.ignore do
    fake_word { Faker::Lorem.word }
  end

  f.sequence(1.to_s) { |n| n }
  f.send(2.to_s) { fake_word.to_s.capitalize }

  initialize_with { attributes.stringify_keys }
end

定义不带块的属性仅适用于1"hello"之类的文字值.

Defining an attribute without a block only works for literal values like 1 or "hello".

更新

如评论中所述,您可能还希望fake_word也使用块.

As mentioned in the comments, you probably want fake_word to use a block as well.

这篇关于具有特质的FactoryGirl工厂可返回带有字符串键的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 12:17