简体   繁体   中英

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. 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:

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.

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]. 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).

The one time I find should respond_to useful is when I have a common interface that I want multiple classes to implement. 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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