开发者

Railstutorial.org Validating presence tests

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 vali开发者_StackOverflowdate 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?


It's so there's one standard attributes map that can be used across all the tests. When a test requires that a value isn't there, it's removed.

Personally, I wasn't convinced it was worth it as it sort of obfuscates things (as you discovered), but there it is.


The point is to only have code relevant for the test case in the test. The only relevant attribute when testing that the user isn't valid without a name is the name attribute. That test should not have to know anything about the email attribute.

Let's say you add validation for the presence of a new field – you'd have to update every test where you build up a User without that field. With the attr hash at the top, you just pop the new field in there, and all your tests are fine.

Creating objects for testing is a common enough problem that there are many solutions, and plenty of discussion about which way is best. I'd suggest you look into factories. Machinist and FactoryGirl are two alternatives that work great with Rails.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜