Rspec 控制器 - 数据库中的对象持久性/作为测试构建的实例

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

我习惯这样测试建筑:

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

除了规范 2 失败,Refund.count 只有 1。我插入了一个 binding.pry,确实第一笔退款已从内存中清除。这是 Rspec 控制器测试的正常行为还是我做错了什么?

确实 Rails 和 RSpec 在每个 运行 上重置了 DB。要使测试生效,您必须真正达到终点 2 次:

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