FactoryGirl for Controller specs
While using Rails scaffold generator, you probably noticed the following controller_spec code:
describe EventsController do
# This should return the minimal set of attributes required to create a valid
# Event. As you add validations to Event, be sure to
# adjust the attributes here as well.
let(:valid_attributes) { { "name" => "MyString" } }
#...
end
You can use FactoryGirl parameters as valid_attributes:
let(:valid_attributes) do
(FactoryGirl.build :event).attributes.symbolize_keys.select {|_, value| !value.nil? }
end
If you need to change some parameters, you can merge it as following:
let(:valid_attributes) do
(FactoryGirl.build :event).attributes.symbolize_keys.select {|_, value| !value.nil? }.
merge(timestamp: Date.today.to_s(:my_custom_format))
end
Written by David Paluy
Related protips
2 Responses
I think FactoryGirl.attributes_for cleaner.
let(:validattributes) { FactoryGirl.attributesfor(:event) }
over 1 year ago
·
Sure! I didn't know about FactoryGirl.attributes_for. Thanks
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Rails
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#