Rspec改变匹配和工厂女孩

时间:2014-10-15 09:53:34

标签: ruby-on-rails-4 rspec-rails rspec3

我正在使用工厂女孩来创建我的对象。我想知道为什么要做以下事情:

RSpec.describe V1::SlotsController, type: :controller do
  let(:valid_slot) { create(:slot) }
  let(:valid_attributes) { attributes_for(:slot) }

  describe "DELETE destroy" do
    it "destroys the requested slot" do
      slot = Slot.create! valid_attributes # not working without this line
      expect {
        delete :destroy, { id: slot.id }
      }.to change(Slot, :count).by(-1)
    end
  end
end

如果我不覆盖插槽,只使用factory_girl创建的插槽,测试将无法通过。为什么?

1 个答案:

答案 0 :(得分:1)

因为let"lazy loaded"。你应该使用

let!(:slot) { create(:slot) }

describe "DELETE destroy" do
  it "destroys the requested slot" do
    expect {
      delete :destroy, { id: slot.id }
    }.to change(Slot, :count).by(-1)
  end
end