【问题标题】:How to stub paperclip file paths in Capybara/Rspec如何在 Capybara/Rspec 中存根回形针文件路径
【发布时间】:2014-05-25 22:39:10
【问题描述】:

对于某些应用程序,我使用 Paperclip 进行文件上传(实际上是 dm-paperclip 风格),并使用 Factory Girl、Rspec、Capybara 进行测试。 我有一个非常简单的“图片”模型工厂,我按照this post 中的建议对我的文件属性进行存根:

FactoryGirl.define do
  factory :picture do
    title "My Picasso"
    description "It's like looking in a mirror."
    picture_file_file_name { 'spec/resources/img_1.jpg' }
    picture_file_content_type { 'image/jpg' }
    picture_file_file_size { 1024 }
  end
end

在使用 Capybara 进行的各种功能测试中,我访问了模板包含图片实例缩略图的页面:

feature "List of Pictures", :js => true  do
  scenario "displays appropriately the index page of the pictures with pagination" do
    FactoryGirl.create_list(:picture, 21)
    visit '/pictures'
    # And more testing...
  end
end

在其中一个模板中使用的部分示例:

=  content_tag_for(:li, picture, :class => 'listed_picture') do
  = link_to picture_path(picture) do
    - if picture.picture_file?
      = image_tag picture.picture_file.url(:thumb)

我现在遇到的问题是,每当我运行规范时,测试都会失败,因为缩略图 url 没有匹配的路由:

No route matches [GET] "/system/picture_files/1/thumb/img_1.jpg"

有没有办法存根 Paperclip 的辅助方法以使测试通过?

提前感谢您的帮助!

【问题讨论】:

  • rubydoc 上有一些回形针的匹配器,我想应该会有帮助。
  • 感谢紫舍的回复。但是,我并不是真的在寻找匹配器来测试我的模型的验证。我的目标是在使用 Capybara/Poltergeist/PhantomJS 渲染模板时,为我的 image_tag 助手相对于工厂存根的模型实例模拟/存根有效路径。再次感谢!
  • 我目前也在努力解决这个问题。你有进步吗?
  • 其实我没有@steel ...

标签: ruby-on-rails rspec paperclip capybara factory-bot


【解决方案1】:

我刚刚经历了这个过程。以下是我解决问题的方法。

首先,我在对象上创建了一个方法来引用图像 URL,既要遵守得墨忒耳定律,又要使测试更容易。对你来说,这可能看起来像:

#picture.rb

class Picture
...
  def picture_file_url(size = nil)
    picture_file.url(size)
  end
...
end

现在我们准备在规范中存根回形针附件 URL:

describe "List of Pictures", :js => true  do
  it "displays appropriately the index page of the pictures with pagination" do
    let(:picture) { create(:picture) }
    allow(Picture).to receive(:picture_file_url) { "url" }
    visit '/pictures'
    # And more testing...
  end
end

希望这对您或某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多