nbi-ya
Last Updated: February 25, 2016
·
1.445K
· dpaluy
3129de6b479cc965513311f1ddcc268a

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
Say Thanks
Respond

2 Responses
Add your response

9907
774cbfa01beba13aa88c12a1c8cec661

I think FactoryGirl.attributes_for cleaner.

let(:validattributes) { FactoryGirl.attributesfor(:event) }

over 1 year ago ·
9908
3129de6b479cc965513311f1ddcc268a

Sure! I didn't know about FactoryGirl.attributes_for. Thanks

over 1 year ago ·