2014-10-03 101 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