1

I need to test that a piece of code executes two sql statements, which I'm doing by saying

  ActiveRecord::Base.connection.should_receive(:execute).with("s1")
  ActiveRecord::Base.connection.should_receive(:execute).with("s2")

However, the code also executes a lot of other statements that I don't care about, which trips up the test. How do I tell Rspec to make sure that s1 and s2 are in the list of executed statements?

Sudhir Jonathan
  • 16,998
  • 13
  • 66
  • 90
  • `"which trips up the test"` -- do you mean that this makes the expectations not work, or do you mean that it makes the actual code not work? – Chris Salzberg Nov 15 '12 at 12:42
  • The expectations don't work - there are a few queries that are executed before and after `s1` and `s2` that trigger an expectation error. – Sudhir Jonathan Nov 17 '12 at 04:10

1 Answers1

2

Update your version of RSpec to 2.12 and you will have access to the and_call_original method (see the documentation and use cases). Using that method, you can stub the execute method of ActiveRecord::Base.connection and make it call through to the original method, and then just add to that the expectations you want:

ActiveRecord::Base.connection.stub(:execute).and_call_original
ActiveRecord::Base.connection.should_receive(:execute).with(:s1)
ActiveRecord::Base.connection.should_receive(:execute).with(:s2)

If for whatever reason you are not using (or don't want to use) the latest version of RSpec, you can achieve the same functionality this way:

execute = ActiveRecord::Base.connection.method(:execute)
ActiveRecord::Base.connection.should_receive(:execute).with(:s1)
ActiveRecord::Base.connection.should_receive(:execute).with(:s2)
ActiveRecord::Base.connection.stub(:execute) { |*args| execute.call(*args) }

Refs:

Community
  • 1
  • 1
Chris Salzberg
  • 27,099
  • 4
  • 75
  • 82
  • Damn. I'm sure this answer is correct, but I find it odd that something this simple would be this difficult. – Sudhir Jonathan Nov 17 '12 at 08:35
  • Updated my answer. I was confused about version numbers, 2.12 is higher than 2.8 so all you have to do is update your version to get access to `and_call_original`. Once you do that, it's just a matter of adding one line: `ActiveRecord::Base.connection.stub(:execute).and_call_original` which will catch all cases, and you can set your expectations without any concern about disrupting the normal flow. – Chris Salzberg Nov 18 '12 at 07:35