This is some of the most verbose code necessary to test two required fields on a model:
# ./spec/models/ignore_user_spec.rb
⋮
describe "required fields" do
subject { IgnoredUser.new }
it "should have an error message for ignored user id" do
subject.valid?
subject.errors[:ignored_user_id].first.should_not be_nil
end
it "should have an error message for user id" do
subject.valid?
subject.errors[:user_id].first.should_not be_nil
end
end
end
⋮
Imagine if there were more than two fields! Here's an improvement:
# ./spec/models/ignore_user_spec.rb
⋮
describe "#validate" do
describe "required field" do
subject { IgnoredUser.new }
it "should have the expected error messages" do
subject.valid?
[:ignored_user_id, :user_id].each do |sym|
subject.errors[sym].first.should_not be_nil
end
end
end
end
⋮
This treats all of the fields as a unit which is less than ideal. Finally if we move the iterative logic outside of the it block we arrive at an elegant solution:
# ./spec/models/ignore_user_spec.rb
⋮
describe "required fields" do
subject { IgnoredUser.new }
[:ignored_user_id, :user_id].each do |sym|
it "should have an error message for #{sym}" do
subject.valid?
subject.errors[sym].first.should_not be_nil
end
end
end
end
⋮