Skip to content

Instantly share code, notes, and snippets.

@betesh
Last active August 29, 2015 14:24
Show Gist options
  • Save betesh/be51479c11fbc9a419c6 to your computer and use it in GitHub Desktop.
Save betesh/be51479c11fbc9a419c6 to your computer and use it in GitHub Desktop.
HasManyAssociationIsCreatedWhenMarkedForDestruction
require "active_record"
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ":memory:")
RSpec.configure do |config|
config.before(:suite) do
Class.new(ActiveRecord::Migration) do
def change
create_table :parents
create_table :children do |t|
t.references :parent_with_autosave
t.references :parent
end
end
end.new.change
end
end
class Parent < ActiveRecord::Base
self.table_name = "parents"
has_many :children
end
class ParentWithAutosave < ActiveRecord::Base
self.table_name = "parents"
has_many :children, autosave: true
end
class Child < ActiveRecord::Base
attr_accessor :string
validates_presence_of :string
end
RSpec.describe do
def when_i_build_a_child_and_mark_it_for_destruction
subject.children.build.mark_for_destruction
end
def and_i_save_and_reload_the_record
subject.save!
subject.reload
end
def when_the_child_is_valid
subject.children[0].string = "ABC"
end
shared_examples_for :failing_test do
it do
when_i_build_a_child_and_mark_it_for_destruction
when_the_child_is_valid
and_i_save_and_reload_the_record
expect(subject.children.count).to eq(0) # This fails when autosave is not used
end
it do
when_i_build_a_child_and_mark_it_for_destruction
and_i_save_and_reload_the_record
expect(subject.children.count).to eq(0)
end
end
describe Parent do
it_behaves_like :failing_test
end
describe ParentWithAutosave do
it_behaves_like :failing_test
end
end
source 'https://rubygems.org'
gem "activerecord", "~> 4.2"
gem "sqlite3"
gem "rspec"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment