Search code examples
ruby-on-railsrspecrspec-rails

Rspec controller - object persistence in database/ which instance as tests build


I'm used to tests building like this:

describe "post to refund first time" do
  it "should have 1 refund" do
    post :refund
    Refund.count.should == 1
  end

  describe "post to refund 2nd time" do
    it "should have 2 refunds" do
      post :refund
      Refund.count.should == 1
    end
  end
end

Except that spec 2 fails, Refund.count is only 1. I inserted a binding.pry and indeed the first refund was cleared from memory. Is this normal behavior for Rspec controller tests or am I doing something wrong?


Solution

  • Indeed Rails and RSpec reset the DB on each run. For your test to work, you have to really hit the endpoint 2 times:

    describe "post to refund first time" do
      it "should have 1 refund" do
        post :refund
        Refund.count.should == 1
      end
    
      describe "post to refund 2nd time" do
        it "should have 2 refunds" do
          2.times { post :refund }
          Refund.count.should == 2
        end
      end
    end