重构respond_to Rspec

时间:2012-07-19 14:19:23

标签: ruby-on-rails ruby rspec tdd

我正在关注Michael Hartl令人惊叹的Rails教程,但我想知道是否有办法在我的用户规范中重构这一点。这是非常重复,并想知道是否有办法干一点。

it { should respond_to(:name) }
it { should respond_to(:email) }
it { should respond_to(:password_digest) }
it { should respond_to(:password) }
it { should respond_to(:password_confirmation) }
it { should respond_to(:remember_token) }
it { should respond_to(:authenticate) }
it { should respond_to(:admin) }
it { should respond_to(:authenticate) }
it { should respond_to(:microposts) }
it { should respond_to(:feed) }
it { should respond_to(:relationships) }
it { should respond_to(:followed_users) }
it { should respond_to(:following?) }
it { should respond_to(:follow!) }
it { should respond_to(:followers) }
it { should respond_to(:reverse_relationships) }

2 个答案:

答案 0 :(得分:4)

[:name, 
 :email, 
 ...
].each do |attrib|
  it { should respond_to(attrib) }
end

答案 1 :(得分:1)

您可以根据需要传递respond_to多个方法名称:

it { should respond_to(:name, :email, :password) }

以这种方式创建单独的每个属性示例的一个好处是,这将运行得更快,因为它是一个示例而不是n个示例。

所有这一切:我建议不要像你这样指定测试中的所有公共属性。这是结构,而不是行为[1]。您的用户模型必须具有某些行为,以保证它需要每个属性。我专注于指定这些行为(使用模型的公共API)而不用担心指定实现细节(例如模型具有什么属性)。

我发现should respond_to有用的一次是我有一个通用接口,我想要多个类来实现。我创建了一个共享的示例组,它以最简单的形式指定该类的实例响应所有属于该接口的部分。

[1] http://blog.davidchelimsky.net/2012/02/12/validations-are-behavior-associations-are-structure/