Hi guys,
I am trying to test a after_commit hook in my rails model with rspec.
However when doing something like:
c = Client.new
c.name = ‘hello’
c.domain = ‘test.com’
c.save
or
c = Factory(:client)
the callback doesn’t get triggered.
I use rails 3 with ruby 1.9.2
Does anybody know how to get the “after_commit” “triggered”
thanxs!
             
            
              
              
              
            
            
                
                
              
           
          
            
            
              What is in the callback? How are you testing that it has/has not been
called?
             
            
              
              
              
            
            
                
                
              
           
          
            
            
              Well i won’t bother you with the details but this should work right?
after_commit :set_directory
def set_directory
puts “hello world”
end
             
            
              
              
              
            
            
                
                
              
           
          
            
            
              ohw and i test by just creating a record (client in this case);
I have tried to do this with:
c = Client.new
c.name = ‘bla’
c.save
or by doing:
c = Factory(:client)
or by doing:
c = Factory.create(:client)
also the other hooks in my model work perfectly:
after_save     :set_upload
after_destroy  :remove_upload
and in the app the after_commit gets called. So it isn’t my code but the
creation with rspec is the problem (something to do with mocking perhaps
? )
             
            
              
              
              
            
            
                
                
              
           
          
            
            
              ok i found a solution!
in your spec;
c = Factory(:client)
c.send(:set_directory)
#yes just call  the method directly (not the most perfect method but it
works! 
for more info check here:
http://apidock.com/rails/v3.0.0/ActiveRecord/Callbacks
             
            
              
              
              
            
            
                
                
              
           
          
          
            
            
              just got stung by this too
the problem is that after_commit callback is called, well, after the
save transaction gets commited :D, which actually never happens in rspec
if you have transactional fixtures on
config.use_transactional_fixtures = true
haven’t found a good solution yet
             
            
              
              
              
            
            
                
                
              
           
          
            
            
              This works great! And it looks like it’s built in to Rails 5+, too.