mock_person = Object.new
mock_person.instance_variable_set(:@first_name, 'John')
mock_person.first_name # NoMethodError: Undefined method `first-name`
mock_person = Object.new
def mock_person.first_name()
return 'John'
end
mock_person.first_name # This works
有更清洁的方法吗?理想情况下,当我使用instance_variable_set
时,我想指定变量应为attr_accessor
。
答案 0 :(得分:1)
不完全确定你要做什么,但要看看Struct
课程。对于你的例子,你可能正在寻找这样的东西:
Struct.new("Person", :first_name)
mock_person = Struct::Person.new('John')
mock_person.first_name #=> "John"
答案 1 :(得分:0)
您使用singleton class在attr_accessor
的{{3}}上致电mock_person
:
mock_person = Object.new
mock_person.singleton_class.class_eval { attr_accessor :first_name }
mock_person.first_name = 'pancakes'
puts mock_person.first_name
# => pancakes
puts mock_person.instance_variable_get(:@first_name)
# => pancakes