ruby-on-rails - 如何在 Capybara/Rspec 中 stub 回形针文件路径

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

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

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"

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

在此先感谢您的帮助!

最佳答案

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

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

#picture.rb

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

现在我们准备在规范中 stub Paperclip 附件 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

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

关于ruby-on-rails - 如何在 Capybara/Rspec 中 stub 回形针文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23860635/

相关文章:

ruby-on-rails - RSpec 中 it block 和 specify block 的区别

ruby-on-rails - RSpec:关联对象的工厂定义

ruby-on-rails - 从 Ruby on Rails 3.2.6 中 Paperclip 生成的文件中删除问号

Android 设备在笔记本电脑上访问本地主机

ruby-on-rails - 谁能告诉我 Ruby 中 Gemspec 文件的用途是什么?

ruby - 使用 Rspec 2 和 Mocha 获取 Rails 3 生成器

ruby-on-rails - 如何在回形针 ruby​​ on rails 中设置默认图像

CSS 在本地工作但不能在 Heroku 上加载

javascript - 成功创建对象后,Ajax 刷新 .erb 代码。

ruby-on-rails - 如何将heroku上回形针的上传目录更改为/tmp?