2014-10-03 100 views
1

我想測試一個載波圖像上傳到模型,使用RSpec /水豚/工廠女孩的Rails。
這個特定的測試測試了圖像應該存在的驗證。資產文件夾的路徑,來自RSpec測試

目前,我有這樣的代碼:

it "should accept a spotlight record with spotlight info" do 
    feature = create :feature, spotlight: true, spotlight_description: "description", spotlight_image: File.open(Rails.root.join "/app/assets/shopstar_logo_stamp.png") 
    expect(feature).to be_valid 
end 

但不知何故,沒有檢測到圖像,我得到這個錯誤:

Failures: 

    1) Feature validations should accept a spotlight record with spotlight info 
    Failure/Error: feature = create :feature, spotlight: true, spotlight_description: "description", spotlight_image: File.open(Rails.root.join "/app/assets/shopstar_logo_stamp.png") 
    Errno::ENOENT: 
     No such file or directory - /app/assets/shopstar_logo_stamp.png 
    # ./spec/models/feature_spec.rb:32:in `initialize' 
    # ./spec/models/feature_spec.rb:32:in `open' 
    # ./spec/models/feature_spec.rb:32:in `block (3 levels) in <top (required)>' 

我如何可以指定一個路徑資產中的圖像並將其用於測試?

或者,或者,測試載波圖像上傳的更好方法是什麼?

+0

您好Marco - 我的回答對您有幫助嗎?如果是這樣,請接受它。 – Anthony 2014-10-06 22:06:25

回答

1

如果這是你真正想要使用水豚這樣從用戶的角度做一個驗收測試/集成測試:

feature 'user uploads image' do 
scenario '#Image' do 
    count = ImageModel.count 
    visit new_image_path 

    attach_file('css_selector_here', File.join(Rails.root, '/spec/support/herst.jpg')) 
    click_button('Submit') 

    expect(page).to have_content('Image uploaded successfully!') 
    expect(ImageModel.count).to eq(count + 1) 
    end 
end 

如果你是一個單元測試後,做這樣的事情與FactoryGirlspec/factories/factory.rb

Factory.define :feature do |f| 
    f.spotlight true 
    f.spotlight_description "description" 
    f.spotlight_image { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'feature', 'images', 'shopstar_logo_stamp.jpg')) } 
end 

現在在你的單元測試,你可以運行測試:

it "should accept a spotlight record with spotlight info" do 
    feature = create :feature 
    expect(feature).to be_valid 
end 
+0

這實際上是一個模型測試。對不起,如果有什麼我不明白問我..我是新來測試 – 2014-10-03 11:14:23

+0

@MarcoPrins沒有問題 - 更新我的答案,包括兩個。 – Anthony 2014-10-03 11:39:43