如何使用 factory_bot 来构建缺乏访问方法的对象?

huangapple go评论57阅读模式
英文:

How to use factory_bot to build objects that lack accessor methods?

问题

class Person
  attr_reader :name # 但没有 attr_accessor
  def initialize(name)
    @name = name
  end
end

FactoryBot.define do
  factory :person do
    name { 'Grace' }
  end
end

如何使用 factory_bot 创建一个 Person?如果尝试 build :person,会出现以下错误:

NoMethodError .. undefined method `name='

我编写了一个自定义构建策略,它可以工作,但我对它不满意,因为我不得不使用 instance_variable_get 来访问私有库对象。

class BuildNew
  def association(runner)
    runner.run
  end

  # @param evaluation [FactoryBot::Evaluation]
  def result(evaluation)
    attributes = evaluation.hash
    model_class = evaluation.instance_variable_get(:@attribute_assigner).send(:build_class_instance).class
    model_class.new(attributes)
  end
end
FactoryBot.register_strategy(:build_new, BuildNew)

<details>
<summary>英文:</summary>

Given a data model that lacks accessor methods,

```ruby
class Person
  attr_reader :name # but NO attr_accessor
  def initialize(name)
    @name = name
  end
end

FactoryBot.define do
  factory :person do
    name { &#39;Grace&#39; }
  end
end

How can I use factory_bot to build a Person? If we try build :person we get:

NoMethodError .. undefined method `name=&#39;

I wrote a custom build strategy which works, but I am not pleased with it because I had to use instance_variable_get to access private library objects.

class BuildNew
  def association(runner)
    runner.run
  end

  # @param evaluation [FactoryBot::Evaluation]
  def result(evaluation)
    attributes = evaluation.hash
    model_class = evaluation.instance_variable_get(:@attribute_assigner).send(:build_class_instance).class
    model_class.new(attributes)
  end
end
FactoryBot.register_strategy(:build_new, BuildNew)

答案1

得分: 2

以下是翻译好的部分:

似乎自定义构建策略是不必要的。可以使用 initialize_with 更简单地完成这个任务。

FactoryBot.define do
  factory :person do
    initialize_with { new(attributes) }
    name { 'Grace' }
  end
end
英文:

It seems the custom build strategy was unnecessary. This can be done much more simply using initialize_with.

FactoryBot.define do
  factory :person do
    initialize_with { new(attributes) }
    name { &#39;Grace&#39; }
  end
end

huangapple
  • 本文由 发表于 2023年6月15日 06:18:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76477924.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定