Non-ActiveRecord objects in FactoryGirl
Creating non-ActiveRecord objects with FactoryGirl is possible. Classically, a constructor is used to set all the data attributes of an object.
class ParsedString
attr_reader :abc, :def
def initialize(string)
@abc, @def = string.split(?|)
end
end
In the above class the attributes are set in the constructor by passing in a string that gets split into two parts on \|
. Lets use instantiate_with
to determine how the object gets instantiated in FactoryGirl.
factory :parsed_string do
initial_value "123|456"
initialize_with { new(initial_value) }
end
And then in the test we can FactoryGirl.build
, like:
ps = FactoryGirl.build(:parsed_string)
expect(ps.abc).to eq 123
expect(ps.def).to eq 456
Tweet