
For complex forms you save time by building your view before you write tests and code for the action in the controller. For example take the following view code:
- form_for :ad_request, @ad_request, :url => ad_request_feature_path do |f|
= f.error_messages :class => 'error'
.form
#publication.form-item.first
- f.fields_for :car_selections do |cs|
= cs.label :headline, "Headline:"
= cs.text_field :headline
Unless you bleed rails you probably can't guess what the params hash posted to the controller will look like. Fortunately for lazybones like me you don't have to guess. Simply create the view, run up your app in dev mode, and post this form. Of course you get an error, but if you look in your app logs you are rewarded with a real life example of your params hash, like this:
{"ad_request"=>{"car_selections_attributes"=>{"0"=>{"headline" => "Mini for $15,000 Driveaway", "id"=>"1"}}}Great. Guess what you should do with that nugget? That's right! Use it as the starting point of your controller test:
it "should save headline" do
car_selection = Factory.create(:car_selection, :id => 1)
ad = Factory.create(:ad_request, :ad_type => 'retail', :car_selections => [car_selection])
post :feature, {"ad_request"=>{"car_selections_attributes"=>{"0"=>{"headline" => "Mini for $15,000 Driveaway", "id"=>"1"}}}
ad.car_selections[0].headline.should == "Mini for $65,000 Driveeaway"
end
This is one of those things that is almost too pedestrian to even talk about, but it can save you time and pain in the long run, especially for the occasional nasty forms with deeply nested objects.
1 comment:
I disagree that this sort of thing is pedestrian. This is the sort of tip that saves small amounts of time that really mount up.
Nice tip
Post a Comment