RSpec笔记 - let 和 let!

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


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


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


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!就可以了。
出处:[url]https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/helper-methods/let-and-let[/url]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值