RSpec:为什么不让工作,但在(每个)之前做什么?

时间:2012-04-19 22:28:40

标签: ruby-on-rails ruby ruby-on-rails-3 rspec rspec2

我有当前的规范:

describe "DELETE 'destroy'" do
  let(:client) { create(:client) }

  #before(:each) do
    #@client = create(:client)
  #end

  it "should delete a client" do
    expect {
      delete :destroy, :id => client
    }.to change(Client, :count).by(-1)
  end

  # ...

end

我使用let时示例失败,但在使用before(:each)时效果正常。

以下是实施代码:

def destroy
  client = Client.find(params[:id])
  if client.destroy
    flash[:success] = "Client deleted successfully"
    redirect_to kong_clients_url
  else
    flash[:error] = "Client not deleted for some reason"
    redirect_to kong_clients_url
  end
end

那么为什么我使用let时会失败?!

1 个答案:

答案 0 :(得分:9)

let是惰性求值的,在访问expect / lambda(+1)中的client属性之前不会创建记录,但是它会立即被删除(-1),所以整体里面的期望计数不会改变。

您可以使用let!强制立即评估:

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