资产文件夹的路径,来自RSpec测试

时间:2014-10-03 10:49:48

标签: ruby-on-rails ruby rspec capybara carrierwave

我正在尝试使用RSpec / capybara / Factory girl for Rails测试载波图像上传到模型。
此特定测试测试图像应存在的验证。

目前,我有这段代码:

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)>'

如何在资源中指定图像的路径并将其用于测试?

或者,测试载波图像上传的更好方法是什么?

1 个答案:

答案 0 :(得分:1)

如果这是验收测试/集成测试,你实际上想要从用户角度使用capybara这样做:

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

如果您正在进行单元测试,请使用FactoryGirl

中的spec/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