代码之家  ›  专栏  ›  技术社区  ›  VP.

rails中的单元测试-带回形针的模型

  •  33
  • VP.  · 技术社区  · 16 年前

    3 回复  |  直到 16 年前
        1
  •  68
  •   Max Chernyak    13 年前

    将文件添加到模型非常简单。例如:

    @post = Post.new
    @post.attachment = File.new("test/fixtures/sample_file.png")
    # Replace attachment= with the name of your paperclip attachment
    

    那样的话,你应该把文件放进你的电脑里 test/fixtures 迪尔。

    我通常在test_helper.rb中做一个小助手

    def sample_file(filename = "sample_file.png")
      File.new("test/fixtures/#{filename}")
    end
    

    @post.attachment = sample_file("filename.txt")
    

    Factory Girl 而不是固定装置,这变得更容易。

        2
  •  16
  •   Alexis    12 年前

    这在Rspec中,但可以轻松切换

    before do # setup
      @file = File.new(File.join(RAILS_ROOT, "/spec/fixtures/paperclip", "photo.jpg"), 'rb')
      @model = Model.create!(@valid_attributes.merge(:photo => @file))
    end
    
    it "should receive photo_file_name from :photo" do # def .... || should ....
      @model.photo_file_name.should == "photo.jpg"
      # assert_equal "photo.jpg", @model.photo_file_name
    end
    

    由于回形针经过了很好的测试,我通常不会太关注“上传”的行为,除非我在做一些不同寻常的事情。但是,我会尽量集中精力确保附件的配置,相对于它所属的模型,满足我的需要。

    it "should have an attachment :path of :rails_root/path/:basename.:extension" do
      Model.attachment_definitions[:photo][:path].should == ":rails_root/path/:basename.:extension"
      # assert_equal ":rails_root/path/:basename.:extension", Model.attachment_definitions[:photo][:path]
    end
    

    所有的好东西都可以在商店里找到 Model.attachment_definitions

        3
  •  1
  •   Ben    9 年前

    我使用FactoryGirl,设置模型。

    #photos.rb
    FactoryGirl.define do
      factory :photo do
        image File.new(File.join(Rails.root, 'spec', 'fixtures', 'files', 'testimg1.jpg'))
      description "testimg1 description"
      end # factory :photo
     end
    

    然后

     # in spec
    
    before(:each) { @user = FactoryGirl.create(:user, :with_photo) }
    

    ...
    the_path= "/:user_id/:basename.:extension"
    if Rails.env.test?
       the_path= ":rails_root/tmp/" + the_path
    end
    has_attached_file :image,  :default_url => ActionController::Base.helpers.asset_path('missing.png'),
    :path => the_path, :url => ':s3_domain_url'
    
    Paperclip.interpolates :user_id do |attachment, style|
       attachment.instance.user_id.to_s
    end
    

    ...

    然后测试附件_定义(由kwon建议)和Dir.glob以检查文件是否保存

     it "saves in path of user.id/filename" do
        expect(Dir.glob(File.join(Rails.root, 'tmp', @user.id.to_s, @user.photo.image.instance.image_file_name)).empty?).to be(false)
     end
    

    通过这种方式,我确信它执行了正确的直接/路径创建等