2011-09-19 62 views
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'

回答

1

您应该使用.send,并追加一个=方法名调用设置,传递值作为第二个参数send

[ 
    :attribute_a, 
    :attribute_b, 
    :attribute_c 
].each do |attr| 
    before do 
    user.send("#{attr}=", 'a_value') 
    end 

你有效地这样做:

user.send('attribute_a=', 'a_value'); 

由于几个原因,您的语法(user.send(:"#{attr}") = 'a_value')是错误/奇怪的:

  • 没有理由来:attr转换为字符串,并将其立即回符号
  • 不能将值分配给的.send
返回值
相关问题