首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

RSpec札记 - let 方法的使用

2013-11-25 
RSpec笔记 - let 方法的使用RSpec 的 let 是一个很方便的用法,但是今天在写一段测试的时候,死活通不过。刚

RSpec笔记 - 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


看起来似乎没什么问题,直到发现了这个 http://stackoverflow.com/a/5359979/960494 ,原来 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

热点排行