I've been working through the tutorials at railstutorial.org, and I was a little stumped by the author's code for section -- 6.2.1 Validating presence.

In the user model, the tutorial adds validates :name, :presence => true. Simple enough.

When the author chooses to write the rspec test, he does something that I thought was a little strange.

describe User do

 before(:each) do
   @attr = { :name => "Example User", :email => "user@example.com" }
 end
 .
 .
 .
 it  "should require a name" do
  no_name_user = User.new(@attr.merge(:name => ""))
  no_name_user.should_not be_valid
 end

end

Why go through the trouble to merge a blank string to @attr when one could get rid of the :each block statement and simply write:

it "should require a name" do
  no_name_user = User.new(:name => "", :email => "user@example.com")
  no_name_user.should_not be_valid
end

I know that the author uses the @attr variable to validate the presence of the email address as well, which is one indication as to why he used the block statement -- to me it makes more sense to follow the structure of the second block quote. Still, I have a feeling there is something that I'm missing here.

Another explanation that crossed my mind is that it helps to use the @attr structure when there are lots of keys to be entered, as opposed to this rather simplistic case of only name and email.

Anyone have any input?

没有正确的解决方案

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top