On Mon, Mar 2, 2009 at 10:23 AM, Bart Zonneveld <[email protected]> wrote: > > On 2-mrt-2009, at 16:50, David Chelimsky wrote: > >> On Mon, Mar 2, 2009 at 8:20 AM, Bart Zonneveld <[email protected]> >> wrote: >>> >>> On 28-feb-2009, at 11:45, MAwiniarski wrote: >>> >>>> Greetings, >>>> >>>> How to write Example which will check if model's variable's >>>> format is valid using :on => :create, like this: >>>> >>>> class User < ActiveRecord::Base >>>> ... >>>> validates_format_of :email, :with => /.../, :on => :create >>>> ... >>>> >>>> Using following code is not right: >>>> it "should ..." do >>>> �...@user = users(:example_user) >>>> �[email protected] = 'invalid_email_format' >>>> �[email protected] >>>> �[email protected]_not be_valid >>>> end >>> >>> Try: >>> >>> it "should ..." do >>> user = User.new # create a NEW user, instead of loading an already saved >>> user from a fixtures file >>> user.email = 'invalid_email_format' >>> user.should_not be_valid >>> user.should have(1).errors_on(:email) >>> end >> >> +1 >> >> I might combine the first two lines: >> >> user = User.create(:email => "invalid_email_format") >> >> That reads more clearly to me because the invalid email format is >> assigned on create, not after. It would have an extra call to valid? >> but I think it's worth it for the clarity of intent in this case. > > Although I agree with the reasoning you display here, I'd *never* validate > any attribute just on create. > I'm pretty sure a user can update his email address somewhere in the site, > but then his email address wouldn't be validated anymore.
FWIW, the OP's code says :on => :create. I also happened to see http://mawiniarski.wordpress.com/2009/02/28/rspec-validation-on-create/, which reinforced for me that this is about validating on create, not general validation. > On a second note, I noticed rspec default generated model specs now use > Model.create!(@valid_attributes) as their default "all is valid" test. > What's the advantage of this approach? I just write @model.attributes = > @valid_attributes; @model.should be_valid, to prevent these specs to > actually hit the db, and therefore speed up my specs a bit. Good point. Wanna submit a patch? http://rspec.lighthouseapp.com Cheers, David > > thanks, > bartz > > _______________________________________________ > rspec-users mailing list > [email protected] > http://rubyforge.org/mailman/listinfo/rspec-users > _______________________________________________ rspec-users mailing list [email protected] http://rubyforge.org/mailman/listinfo/rspec-users
