简体   繁体   English

重构response_to Rspec

[英]Refactoring respond_to Rspec

I'm following Michael Hartl's amazing Rails Tutorial, but am wondering if there is a way to refactor this in my user's spec. 我正在关注Michael Hartl令人惊叹的Rails教程,但是想知道是否有一种方法可以在用户规范中进行重构。 It's awfully repetitive and wondering if there's a way to DRY it up a bit. 这是非常重复的,想知道是否有办法将其干燥。

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) }
[:name, 
 :email, 
 ...
].each do |attrib|
  it { should respond_to(attrib) }
end

You can pass respond_to as many method names as you want: 您可以根据需要传递respond_to多个方法名称:

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

One benefit of doing it this way over creating a separate example per attribute is that this will run faster because it's one example instead of n examples. 与通过每个属性创建一个单独的示例相比,以这种方式进行操作的一个好处是运行速度更快,因为它是一个示例而不是n个示例。

All that said: I'd recommend against specifying what all the public attributes are in your tests like this. 话虽如此:我建议您不要像这样指定测试中所有公共属性是什么。 This is structure, not behavior[1]. 这是结构,而不是行为[1]。 There must be some behavior your user model has that warrants it needing each attribute. 您的用户模型必须具有某些行为,以保证需要每个属性。 I'd focus on specifying those behaviors (using the public API of the model) and not worry about specifying the implementation details (eg what attributes the model has). 我将专注于指定这些行为(使用模型的公共API),而不必担心指定实现细节(例如,模型具有哪些属性)。

The one time I find should respond_to useful is when I have a common interface that I want multiple classes to implement. 我发现should respond_to有用的一次是当我有一个想要多个类实现的通用接口时。 I create a shared example group that, in its simplest form, will specify what that an instance of the class responds to all the that are part of the interface. 我创建了一个共享的示例组,该组以其最简单的形式指定该类实例对接口中所有响应的响应。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM