This is using Rails 4.2.0, Ruby 2.2.0.
What I'd like to do is use the data contained in a fixture object to verify that duplicates are caught before insertion into the same database:
test "identical entries should be impossible to create" do
dup_entry = Entry.new(entries(:test_entry))
assert_not dup_entry.save
end
(where Entry
is a well-defined model with a controller method .new
, and test_entry
is a fixture containing some valid Entry
instance.)
Unfortunately, this doesn't work because entries(:test_entry)
is going to be an Entry
, not a hash accepted by Entry.new
.
I know that I can access fixture properties with an expression of the form fixture_objname.property
in the associated tests, since whatever is specified in the YAML will automatically be inserted into the database and loaded. The problem with this is that I have to manually retype a bunch of property names for the object I just specified in the YAML, which seems silly.
The documentation also says I can get the actual model instances by adding self.use_instantiated_fixtures = true
to the test class. However, there don't seem to be any instance_methods
that will dump out the fixture's model instance (test_entry
) in a hash format to feed back into the .new
method.
Is there an idiomatic way to get what I want, or a different, easier way?
I believe you're looking for something like:
entries(:test_entry).attributes
entries(:test_entry).attributes.class # => Hash
You can also remove properties if needed:
entries(:admin).attributes.except("id")
Hope this helps.