我有当前的规范:
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时会失败?!
答案 0 :(得分:9)
let
是惰性求值的,在访问expect / lambda(+1)中的client
属性之前不会创建记录,但是它会立即被删除(-1),所以整体里面的期望计数不会改变。
您可以使用let!
强制立即评估:
let!(:client) { create(:client) }