質問

私はペーパークリップを使用して、画像とモデルのためのテストを書くことをしようとしています。私は、テストフレームワークのデフォルト、無shouldaやRSpecのを使用しています。この文脈では、どのように私はそれをテストする必要がありますか?私は実際にファイルをアップロードする必要がありますか?どのように私は、フィクスチャにファイルを追加する必要がありますか?

役に立ちましたか?

解決

モデルへのファイルの追加死んで簡単です。たとえばます:

@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")
あなたはファクトリー・ガールのようなものを使用している場合は、

の代わりに、器具の、これがさらに容易になります。

他のヒント

これは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で見つけることができます。

私が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

...

次に、(クォンによって示唆されるように)attachment_definitionsの両方をテストし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

私はその、正しいdirecty /パスを行うと確信しているこの方法は、

などを作成します
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top