【问题标题】:Rails test: test image_tag on viewRails 测试:在视图上测试 image_tag
【发布时间】:2015-04-09 12:53:01
【问题描述】:

我正在编写视图测试,我想测试一个图像:

<%= image_tag "icon.png", class: "img-responsive" %>

所以我做了这个测试,但没有工作:

it 'app logo' do
  render
  assert_select 'img.img-responsive[src=?]', asset_path('icon.png')
end

如果我使用以下方法,它会起作用,但我认为这不是正确的做法:

it 'app logo' do
  render
  assert_select 'img.img-responsive[src=?]', '/assets/icon.png'
end

可能是什么问题? 这是使用 rspec 测试它的正确原因吗?

【问题讨论】:

  • 错误跟踪是什么?
  • 它只是未能通过测试并在呈现的页面上进行检查:&lt;img class="img-responsive" src="/assets/icon-e2b3082e88fb48115dd034ffa716fbfc.png" alt="Icon"&gt;

标签: ruby-on-rails unit-testing view rspec


【解决方案1】:

用水豚试试这个:

page.should have_selector(:xpath, XPATH_OF_THE_IMAGE_ELEMENT)

【讨论】:

  • 用 capybara 我可以做 it { expect(response.body).to have_selector('img.img-responsive') } 但我不能检查 src 或者至少我不知道该怎么做。
  • 您可以从浏览器中检查元素(img 标签),然后右键单击元素代码。单击“复制 Xpath”。在上述代码中使用这个 xpath
  • 但仍然无法检查图像是否正确
【解决方案2】:

我不确定问题中的方法是正确还是不正确,但您可以尝试以下方法:

expect(response.body).to include('icon.png')
expect(response.body).to have_css(".img-responsive")

【讨论】:

  • 这种方法有效,但它不测试元素的类型或类
  • 你是对的,我已经编辑了我的答案,包括对元素类的测试。
  • 但该代码不会测试图像是否具有该类。我可以在渲染的任何其他元素中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-20
  • 2013-06-12
  • 2015-10-31
相关资源
最近更新 更多