Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails fixtures :has_many and :belongs_to

How do I create sample data in my .yml for has_many and belongs_to variables.

This is a sample adding these files into a simple rails new lab command in the terminal. I don't really know how to explain this in english. But I hope my code shows enough detail to get the point across.

man.rb

class Man < ActiveRecord::Base
  attr_accessible :name
  has_many :items
end

item.rb

class Item < ActiveRecord::Base
  attr_accessible :name
  belongs_to :man
end

men.yml

one:
  name: ManOne
  #items: one, two

two:
  name: ManTwo
  #items: one, two

items.yml

one:
  name: ItemOne

two:
  name: ItemTwo

man_test.rb

require 'test_helper'

class ManTest < ActiveSupport::TestCase
  def test_man
    Man.all.each do |man|
      puts man.name.to_s + ": " + man.items.to_s
    end
    assert true
  end
end
like image 798
Konrad Wright Avatar asked Mar 27 '14 22:03

Konrad Wright


People also ask

What are rails fixtures?

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.

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.

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.


1 Answers

Have a look to fixtures docs, you can do somehting like:

men.yml

man_one:
  name: ManOne

man_two:
  name: ManTwo

items.yml

item_one:
  name: ItemOne
  man: man_one

item_two:
  name: ItemTwo
  man: man_one

item_three:
  name: ItemThree
  man: man_two

Update

It seems you don't have the man_id in the table column. You should create a migration to do so:

rails g migration AddManIdToItem man_id:integer

and run the migration: bundle exec rake db:migrate

like image 141
Sergio A. Avatar answered Oct 05 '22 00:10

Sergio A.