1
我使用Ruby on Rails的3.0.9和RSpec 2.我想通过以下方式重构了一些规范文件(为了用更少的代码相似的类对象来测试属性值):如何设置“以编程方式”“迭代”每个类对象属性的值?
[
:attribute_a,
:attribute_b,
:attribute_c
].each do |attr|
before do
# HERE I would like to set the "current" 'attr' related to the
# class object instance 'attribute_<letter>' (read below for
# more information) each time the iterator is called (note: all
# following attributes are NOT attr_accesible - for that reason
# I use the 'user.attribute_<letter>' in the 'before do'
# statement)
#
# # Iteration 1
# user.attribute_a = 'a_value'
# # No changes to 'user.attribute_b'
# # No changes to 'user.attribute_c'
#
# # Iteration 2
# # No changes to 'user.attribute_a'
# user.attribute_b = 'a_value'
# # No changes to 'user.attribute_c'
#
# # Iteration 3
# # No changes to 'user.attribute_a'
# # No changes to 'user.attribute_b'
# user.attribute_c = 'a_value'
# Maybe I should make something like the following but that, as well
# as the 'send' method must be used, doesn't work (the below code-line
# is just an example of what I would like to do).
#
# user.send(:"#{attr}") = 'a_value'
end
...
end
我如何改进上面的代码,以达到我的目标(我指的是user.send(:"#{attr}") = 'a_value'
部分,以“编程”方式设置 - 即为每次迭代设置不同的属性值 - 每个用户属性值为'a_value'
)?