Last active
January 28, 2016 20:36
-
-
Save a-leung/64f8942367b6c3566500 to your computer and use it in GitHub Desktop.
rspec and ActiveRecord::Base.transaction testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def set_new_name_on_items? | |
success = ActiveRecord::Base.transaction do | |
model.items.each do |i| | |
i.name = 'new name' | |
i.save or raise ActiveRecord::Rollback | |
end | |
!!success | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
it 'returns false on a single failing transaction' do | |
items = [ item_a, item_b ] | |
model = Fabricate(:model, items: items) | |
item_b.stub(:save!).and_return(false) | |
expect(model.set_new_name_on_items).to be false | |
end | |
it 'returns true on all save transaction' do | |
items = [ item_a, item_b ] | |
model = Fabricate(:model, items: items) | |
expect(model.set_new_name_on_items).to be true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
actually, best way to stub this is:
.stub(:create_or_update)
:From the docs:
so,
save
andsave!
are slightly different but both callcreate_or_update
.