Search code examples
ruby-on-rails-3unit-testingfixtures

Generate new record from fixture


I have a fixture called "group":

one:
   customer: one
   name: MyString

In one test I need a couple more so I would like to do something like:

  (1..3).each { |t| Group.create!(groups(:one), name: "Group #{t}")}

Is there a way to do something like that with fixtures? (The above of course doesn't work). I know that I could use factories but I want to keep using fixtures.


Solution

  • your second example is a kind of Factory.

    if you want to use (yaml) fixtures, you can simply produce them with a script similar to your second example, along the lines of:

    y = {"two" => {"customer" => "two", "name" => "londiwe"}}.to_yaml   
    fi = open("groups.yml", "w")
    fi.write(y)
    fi.close
    

    edit after comment: if you just want to take attributes from an existing record and create new records based on that one record, use clone:
    1. first find the record you want to clone:

    orig = Group.find_by_customer("one")
    

    2. create the clone, change its attributes and save it

    (1..3).each do 
         tmp_clone = orig.clone 
         tmp_clone.name = "two"
         tmp_clone.save
    end