【问题标题】:How do I stub a File object with Rspec如何使用 Rspec 存根 File 对象
【发布时间】:2012-11-20 04:24:02
【问题描述】:

我在规范中有以下内容:

before do 
  @item = Item.new( title: "Lorem ipsum", 
    image: File.new(Rails.root.join('app', 'assets', 'images', 'rails.png')))
end

相关的规范运行大约需要 30 秒,但是当我从哈希中删除 image: File.new() 时,我的测试运行不到 1 秒!

所以File.new() 给我的规范增加了负担,如果可能的话我想把它存根,但是当我尝试这个时:

image: File.stub(Rails.root.join('app', 'assets', 'images', 'rails.png'))) 

我在测试输出中看到以下错误:

 Failure/Error: image: File.stub(Rails.root.join('app', 'assets', 'images', 'rails.png'))) }
 NoMethodError:
   undefined method `to_sym' for #<Pathname:0xae767d8>

我会很感激这里的任何建议。 FWIW,图片上传由回形针处理。

【问题讨论】:

    标签: ruby-on-rails rspec stub


    【解决方案1】:

    我会这样做:

    @item = Item.new( title: "Lorem ipsum")
    file = double('file', :size => 0.5.megabytes, :content_type => 'png', :original_filename => 'rails')
    @item.stub(image).and_return(file)
    

    【讨论】:

      【解决方案2】:

      看看 Rails API 中的 fixture_file_upload:

      http://apidock.com/rails/ActionDispatch/TestProcess/fixture_file_upload

      【讨论】:

        【解决方案3】:

        对不起,这不是模拟文件。您想要制造一个对象并将一个真实文件附加到它上面——这不是一个模拟,而且这些解决方案都没有模拟一个文件对象。

        您绝对应该使用 gem 来伪造测试数据,例如 factory girl railsfabrication

        ..当你这样做时,Tom L 的答案是最好的:使用fixture_file_upload

        【讨论】:

          【解决方案4】:

          也可以像这样存根附件: 将其添加到规范/支持中

          module PaperclipStub
            def stub_paperclip_attachment(model, attachment)
              model.any_instance.stub(attachment.to_sym).and_return File.join(Rails.root, 'spec', 'fixtures', 'file.png')
              model.any_instance.stub("#{attachment}_file_name".to_sym).and_return File.join(Rails.root, 'spec', 'fixtures', 'file.png')
            end
          end
          

          在 spec_helper.rb 中

          config.include PaperclipStub # Include custom paperclip_attachment stub
          

          并在规范中使用它:

          it "should be valid" do
              stub_paperclip_attachment(Image, :image)
              Image.new.should be_valid
            end
          

          【讨论】:

            猜你喜欢
            • 2015-04-16
            • 2014-06-26
            • 1970-01-01
            • 2015-08-31
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-29
            相关资源
            最近更新 更多