使用RSpec在Rails中测试视图助手

The*_*hop 2 ruby rspec ruby-on-rails helper

我需要测试以下帮助器:

def display_all_courses
  @courses = Course.all

  output =  ""

  for course in @courses do
    output << content_tag(:li, :id => course.title.gsub(" ", "-").downcase.strip) do
      concat content_tag(:h1, course.title)
      concat link_to("Edit", edit_course_path(course))
    end
  end

  return output
end 
Run Code Online (Sandbox Code Playgroud)

我想知道是否有办法可以测试这个输出.基本上,我只是想测试帮助器给我正确数量的li元素,也许是没有任何课程的情况.

我的第一个想法是做这样的事情:

describe DashboardHelper do
  describe display_all_courses do
    it "should return an list of all the courses" do
      7.times{Factory(:course)
      html = helper.display_all_courses
      html.should have_selector(:li)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

这很好用.但是,如果我将:count选项添加到have_selector调用它突然失败,有人可以帮我弄清楚为什么会这样吗?

Sup*_*ish 5

我相信你所寻找的是has_tag和with_tag RSpec助手

describe DashboardHelper do
  describe display_all_courses do
    it "should return an list of all the courses" do
      7.times{ Factory(:course) }
      helper.display_all_courses.should have_tag('ul') do
        with_tag('li', 3)
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)