是否可以在rspec特征测试中调用truncate方法?

时间:2013-08-06 21:18:01

标签: ruby-on-rails-3 capybara rspec2 truncate

我正在使用Rails 3.2,Rspec 2和capybara 2.

我在我的网页中截断了一串正文,并希望在我的功能规范中对此进行测试。

有人可以建议如何做到这一点,因为我似乎无法在我的测试中调用truncate,因为它一直说它是一个未定义的方法,我真的不想在我的测试套件中有一长串截断的文本;只应用truncate函数就足够了。

我已尝试使用helper.truncate()view.truncate(),但无济于事。

如果有办法生成一个lorem ipsum字符串并截断它以便以某种方式进行比较,我在测试的其他部分使用了Faker gem。

查看代码:

<dd><%= truncate(project.details, :length => 100) %></dd>`

测试代码

it { should have_selector('dd', @project.details) }

当我显示完整的详细信息文本时,此测试测试工作正常,但因为我决定只显示此视图中的前100个字符我不知道如何测试这个而不必将细节设置为固定字符串,然后以某种方式检查它的截断版本。

由于

中校

3 个答案:

答案 0 :(得分:1)

truncateString类的Rails扩展,因此在Ruby或RSpec中不可用。可能有某种方式“包含”它,但我很熟悉如何做到这一点。事实证明,定义是自包含的,因此自己定义它是很简单的。以下是http://apidock.com/rails/String/truncate的来源。它被定义为一个实例方法,所以如果你想将它与传入的字符串一起使用,你需要包含一个text参数来代替引用self,这是当前在第一个身体的一条线。

# File activesupport/lib/active_support/core_ext/string/filters.rb, line 38
  def truncate(length, options = {})
    text = self.dup
    options[:omission] ||= "..."

    length_with_room_for_omission = length - options[:omission].mb_chars.length
    chars = text.mb_chars
    stop = options[:separator] ?
      (chars.rindex(options[:separator].mb_chars, length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission

    (chars.length > length ? chars[0...stop] + options[:omission] : text).to_s
  end

答案 1 :(得分:1)

这对我有用:)

require 'active_support/core_ext/string/filters'

it { should have_selector('dd', @project.details.truncate(100)) }

答案 2 :(得分:1)

最后,我决定如果在更大的屏幕上查看页面,那么更宽的列将允许显示更多细节,并减少截断文本的需要,所以我决定使用css修剪细节使用以下内容减少屏幕上显示的内容:

.text-trim {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}