Skip to content

Instantly share code, notes, and snippets.

@bobisme
Created February 27, 2018 00:09
Show Gist options
  • Save bobisme/ae00be3691ccb0bbbceacf98e163f65c to your computer and use it in GitHub Desktop.
Save bobisme/ae00be3691ccb0bbbceacf98e163f65c to your computer and use it in GitHub Desktop.
require 'rails_helper'
# class Cat < ApplicationRecord
# has_many :cat_toy
# has_many :toys, through: :cat_toy, dependent: :destroy
# end
#
# class Toy < ApplicationRecord
# end
#
# class CatToy < ApplicationRecord
# belongs_to :cat
# belongs_to :toy
# end
describe 'Cat' do
describe '#toys' do
let(:cat) { Cat.create!(name: 'Ezzie') }
let(:toys) { (1..3).map { |x| Toy.create!(name: "Toy #{x}") } }
it 'can have many toys' do
cat.toys = toys[0..1]
cat.reload
expect(cat.toys).to eq [toys[0], toys[1]]
end
it 'creates a new CatToy whenever it gets a toy' do
cat.toys = toys[0..1]
expect(CatToy.count).to eq 2
end
it 'deletes relevant CatToys when toys are removed' do
cat.toys = toys[0..1]
cat.toys = []
expect(CatToy.count).to eq 0
end
it 'does not delete the toys themselves' do
cat.toys = toys[0..1]
cat.toys = []
expect(Toy.count).to eq 3
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment