---
title: "RSpec笔记 - let 和 let!"
author: "tiroc"
date: "2013-11-24T00:20:30Z"
tags: []
categories: ["编程语言"]
slug: "rspec-let-let"
draft: false
lastmod: "2013-11-27T11:11:44Z"
id: 1979888
url: "https://tiroc.iteye.com/blog/1979888"
---

RSpec 的 let 是一个很方便的用法，但是今天在写一段测试的时候，死活通不过。刚开始还怀疑是 PostgreSQL 的查询语法有什么特殊的（刚用PostgreSQL，还不熟），结果查了一圈发现，是我用错了 let 语句。来看看这段测试


```ruby

  describe "scope" do
    let(:articles) { rand(2..10).times.map { create(:article) } }
    let(:drafts) { rand(2..10).times.map { create(:draft) } }

    it "published should match all published articles" do
      expect(Article.published.to_a).to eq(articles)
    end

    it "drafts should match all drafts" do
      expect(Article.drafts.to_a).to eq(drafts)
    end
  end

```


看起来似乎没什么问题，直到发现了这个 <http://stackoverflow.com/a/5359979/960494> ，原来 let 和 before(:each) 有一个区别就是，let 语句的 block 只有在调用到对应的变量时才运行。所以，我调换了一下顺序，就好了。


```ruby

  describe "scope" do
    let(:articles) { rand(2..10).times.map { create(:article) } }
    let(:drafts) { rand(2..10).times.map { create(:draft) } }

    it "published should match all published articles" do
      expect(articles).to eq(Article.published.to_a)
    end

    it "drafts should match all drafts" do
      expect(drafts).to eq(Article.drafts.to_a)
    end
  end

```


---------------------------------

Update: 2013-11-27
只需把原测试代码中的let换成let!就可以了。
出处：<https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/helper-methods/let-and-let>