【问题标题】:Rspec Change Matcher and factory girlRspec Change Matcher 和工厂女孩
【发布时间】:2014-10-15 09:53:33
【问题描述】:

我正在使用工厂女孩来创建我的对象。我想知道为什么我必须执行以下操作:

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

如果我不覆盖slot,只使用factory_girl创建的那个,测试不会通过。为什么会这样?

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 太棒了,谢谢。总是使用 let 是否可以节省(性能方面)! (例如 GET、PATCH)还是应该只在必要时使用(例如 DELETE)?
    • 您应该避免在测试中创建不必要的记录以进行更快的测试。在您的示例中,必须在运行期望块之前创建 slot。但是请注意这里let! 不在describe "DELETE destroy" 范围内,如果您添加更多描述,那么即使不使用,每次都会创建slot
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    相关资源
    最近更新 更多