Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to generate Rails fixtures from an existing set of models?

I have a Rails 2.x app with no tests. I can write out the tests manually, but is there a way to generate fixtures automatically? It would be nice to not have to type all that out by hand.

I could run script/generate again for all the models, but everything already exists and if I understand generators correctly, I'd still have to type in all the attributes.

I thought about running the Rails console and doing for example...

>> y VendorUser.all.rand

That would give me some YAML with all the attributes, but they'd be out of order and it's still pretty time-consuming.

Can anyone suggest a more efficient option?

like image 964
Ethan Avatar asked May 11 '11 22:05

Ethan


People also ask

What is the benefit of using factories over fixtures?

It has a benefit of clarity and low overhead. Like I said above, I've definitely used factories more than fixtures. My main reason is that when I use factories, the place where I specify the test data and the place where I use the test data are close to each other. With fixtures, on the other hand, the setup is hidden.

What are RSpec fixtures?

Fixtures allow you to define a large set of sample data ahead of time and store them as YAML files inside your spec directory, inside another directory called fixtures. When you're test sweep first starts up RSpec will use those fixture files to prepopulate your database tables.

How do fixtures work rails?

Fixtures are data that you can feed into your unit testing. They are automatically created whenever rails generates the corresponding tests for your controllers and models. They are only used for your tests and cannot actually be accessed when running the application.

What exactly are harnesses and fixtures in the Ruby?

14) What exactly are Harnesses and Fixtures in the Ruby? These are basically the supporting codes with the help of which the users can easily write and can run the test cases. With the help of a rake, the users can then simply proceed with the automated tests.


1 Answers

Here is a rake task to generate fixtures.

desc "extracting data for fixtures"
task :extract_fixtures => :environment do
  sql  = "SELECT * FROM %s"
  skip_tables = ["schema_info","schema_migrations"]
  ActiveRecord::Base.establish_connection
  (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name|
    i = "000"
    File.open("#{RAILS_ROOT}/test/fixtures/#{table_name}.yml", 'w' ) do |file|
      data = ActiveRecord::Base.connection.select_all(sql % table_name)
      file.write data.inject({}) { |hash, record|
        hash["#{table_name}_#{i.succ!}"] = record
        hash
      }.to_yaml
    end
  end
end
like image 139
radha Avatar answered Sep 24 '22 20:09

radha