Last Updated: February 25, 2016
·
1.721K
· dpaluy

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

2 Responses
Add your response

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 ·