如何在轨道上使用Rspec Capybara和Factory Girl在Ruby中计算循环



这个问题是关于测试我进行的,以验证用户页面中的所有50个微柱都显示

我有这个rsspec代码:

          before(:all) { 50.times {FactoryGirl.create(:micropost, 
                                   user:user, content: "Lorem Ipsum") } }

我想让每个内容都更加动态,比如:

"Lorem Ispum 0"
"Lorem Ipsum 1"
"Lorem Ipsum 2"
...

我试着写:

let(:count_helper) { 0 }
before(:all) { 50.times {FactoryGirl.create(:micropost, 
                                       user:user, 
                                       content: "Lorem Ipsum #{count_helper}") 
                         count_helper += 1} }

它在这里失败了:

count_helper += 1 

我怎样才能把它写对?

let(:count_helper) { 0 }
before(:all) { 50.times {FactoryGirl.create(:micropost, 
                                       user:user, 
                                       content: "Lorem Ipsum #{count_helper}");
                                       count_helper += 1 } }

注意FactoryGirl.create(:micropost, user:user, content: "Lorem Ipsum #{count_helper}") 末尾的分号

由于您使用的是单行块语法,因此应该明确地告诉Ruby count_helper += 1是另一个语句。

这就是应该如何编写代码:

    before(:all) { 50.times do |count|
                     FactoryGirl.create(:micropost, user:user, 
                     content: "Lorem Ipsum #{count}") 
                   end }

我有两个错误:

  1. {}内部只允许一个代码行时创建2个代码行-我将其更改为do ... end

  2. 我在循环中添加了|count|变量,这有助于我通过循环进行计数

最新更新