Looking through a tutorial on controller testing the author gives an example of an rspec test testing a controller action. My question is, why did they use the method attributes_for over build? There is no clear explanation why attributes_for is used besides that it returns a hash of values.
it "redirects to the home page upon save" do
post :create, contact: Factory.attributes_for(:contact)
response.should redirect_to root_url
end
The tutorial link is found here: http://everydayrails.com/2012/04/07/testing-series-rspec-controllers.html The example is found at the beginning topic section Controller testing basics
attributes_forwill return a hash, whereasbuildwill return a non persisted object.Given the following factory:
Here is the result of
build:and the result of
attributes_forI find
attributes_forvery helpful for my functional test, as I can do things like the following to create a user:When using
build, we would have to manually create a hash of attributes from theuserinstance and pass it to thepostmethod, such as:I usually use
build&createwhen I directly want objects and not an attributes hashLet me know if you need more details