Skip to content

Instantly share code, notes, and snippets.

@xuncheng
Created July 2, 2013 10:30
Show Gist options
  • Save xuncheng/5908269 to your computer and use it in GitHub Desktop.
Save xuncheng/5908269 to your computer and use it in GitHub Desktop.
rspec testing has_many :through association
# video.rb
class Video < ActiveRecord::Base
has_many :categorizations
has_many :categories, through: :categorizations
end
# category.rb
class Category < ActiveRecord::Base
has_many :categorizations
has_many :videos, through: :categorizations
end
# categorization.rb
class Categorization < ActiveRecord::Base
belongs_to :video
belongs_to :category
end
# video_spec.rb
require 'spec_helper'
describe Video do
it "have created a relationship with Category" do
video = Video.create(title: "futurama", description: "fry, a pizza guy is accidentally frozen in 1999")
category = Category.create(name: "comedies")
video.categories << category
Categorization.first.video.should == video
Categorization.first.category.should == category
end
it "have categories" do
video = Video.create(title: "futurama", description: "fry, a pizza guy is accidentally frozen in 1999")
category = Category.create(name: "comedies")
video.categories << category
video.categories.should == [category]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment