How do I raise an exception in Rspec while running a method?
<p>I have an ActiveRecord Transaction that I am trying to test, but I'm having some difficulty understanding exactly how to write my Rspec test. Here is an example of what I'm going for:</p>

<pre><code>it "does not change the model count" do
  expect(Model.count).to be(0)
  expect {
    MyClass.my_method(arg1, arg2)
  }.to raise_error
  expect(Model.count).to be(0)
end
</code></pre>

<p>While <code>my_method</code> is running, there are several objects being saved to the DB. I want to raise an exception <em>while</em> this method is running in order to invoke the transaction rollback.</p>

<p>What is the best way to go about raising this exception?</p>

<p><strong>EDIT:</strong></p>

<p>I appreciate everyone taking the time to give me input. My goal was to test a transaction rollback. I was calling two different methods inside a transaction, and I wanted to make sure that if an error arose in the second method the data written to the DB in the first method did not persist.</p>

<p>I got this to work as I needed, though I recognize it's contrived.</p>

<pre><code>class MyClass

  def self.save_my_values(arg1, arg2)
    parsed = parse(arg1)

    ActiveRecord::Base.transaction do
      some_method(parsed, arg2)
      my_method(parsed, arg2)
    end
  end
end
</code></pre>

<p>And here is the code in the spec:</p>

<pre><code>context "when there is an error" do
  before do
    allow(MyClass).to receive(:my_method).and_raise(StandardError)
  end

  it "does not change the model count" do
    expect(Model.count).to be(0)
    expect {
      MyClass.my_method(arg1, arg2)
    }.to raise_error(StandardError)
    expect(Model.count).to be(0)
  end
end
</code></pre>

<p>I'll be refining it further, but this was the starting point I was looking for. Thank you again!</p>