英文:
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 { 'Grace' }
end
end
How can I use factory_bot
to build a Person
? If we try build :person
we get:
NoMethodError .. undefined method `name='
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 { 'Grace' }
end
end
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论