【问题标题】:Testing view helpers in Rails with RSpec使用 RSpec 在 Rails 中测试视图助手
【发布时间】:2010-08-23 02:46:51
【问题描述】:

我需要测试以下助手:

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 

我想知道是否有一种方法可以测试它的输出。基本上,我只是想测试帮助器是否为我提供了正确数量的 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

这很好用。但是,如果我将 :count 选项添加到 have_selector 调用它突然失败,谁能帮我弄清楚这是为什么?

【问题讨论】:

    标签: ruby-on-rails ruby rspec helper


    【解决方案1】:

    我相信您正在寻找的是 have_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
    

    【讨论】:

      【解决方案2】:

      也许将 html 视为 xml 会有所帮助? 在这种情况下,this link 会有所帮助。

      它定义了一个匹配器have_xml,这可能正是您所需要的。 虽然我知道如果have_tag 也能在字符串上工作会更好。

      【讨论】:

        【解决方案3】:

        显然模板是最好的方法。

        【讨论】:

        • 你能解释一下这个答案吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-14
        • 2011-04-02
        • 1970-01-01
        相关资源
        最近更新 更多