RoR和Rspec使用while循环设置测试

时间:2013-09-01 21:02:44

标签: ruby-on-rails rspec tdd

好的,所以我想创建一个测试,检查所有页面都有一定的标题。但是我认为如果我可以在array中包含页面标题会很好,这样我就不必为每个页面复制块。这样我就可以通过修改pages array来测试其他页面。

我遇到的问题是页面变量没有在测试中进行插值。那么这是语法错误还是Rspec不允许在it should do...块内进行插值?

describe "LayoutLinks" do

    page = ["home", "contact", "about", "help"]
    i = page.count
    x = 0

    while x < i  
        it "should have a #{page[x]} page" do
        get "#{page[x]}"
        response.should have_selector("title", :content => "#{page[x]}")
        end
    x += 1
    end

end

测试显示以下失败:

  1) PagesController LayoutLinks should have a help page
     Failure/Error: get "#{page[x]}"
     ActionController::RoutingError:
       No route matches {:controller=>"pages", :action=>""}
     # ./spec/controllers/layout_links_spec.rb:14:in `block (3 levels) in <top (required)>'

  2) PagesController LayoutLinks should have a contact page
     Failure/Error: get "#{page[x]}"
     ActionController::RoutingError:
       No route matches {:controller=>"pages", :action=>""}
     # ./spec/controllers/layout_links_spec.rb:14:in `block (3 levels) in <top (required)>'

  3) PagesController LayoutLinks should have a about page
     Failure/Error: get "#{page[x]}"
     ActionController::RoutingError:
       No route matches {:controller=>"pages", :action=>""}
     # ./spec/controllers/layout_links_spec.rb:14:in `block (3 levels) in <top (required)>'

  4) PagesController LayoutLinks should have a home page
     Failure/Error: get "#{page[x]}"
     ActionController::RoutingError:
       No route matches {:controller=>"pages", :action=>""}

这里的失败错误是显而易见的。它不应该说得到"#{page[x]}",而应该是get homeget about等......

我该如何补救?谢谢您的帮助。非常感谢:)

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

describe "LayoutLinks" do
  %w(home contact about help).each do |page|
    it "should have a #{page} page" do
      get page
      response.should have_selector("title", content: page)
    end
  end
end

%w创建一个字符串数组(空格成为逗号,所以你得到[“home”,“contact”等])