总 Rspec 菜鸟在这里。今晚写我的第一个测试。
我有一个名为 Image 的模型。使用回形针,我附加了一个名为 photo 的文件。标准的东西。我已经运行了回形针生成器,并且在生产和测试模式下一切正常。
现在我有一个名为 image.rb 的规范文件,它看起来像这样(它是由 ryanb 的 nifty_scaffold 生成器创建的):
require File.dirname(__FILE__) + '/../spec_helper'
describe Image do
it "should be valid" do
Image.new.should be_valid
end
end
这个测试失败了,我意识到这是因为我的模型验证(即 validates_attachment_presence)
我得到的错误是:
Errors: Photo file name must be set., Photo file size file size must be between 0 and 1048576 bytes., Photo content type is not included in the list
那么我如何告诉 rspec 在运行我的测试时上传照片?
我猜这与固定装置有关……但也许不是。我试过和他们一起玩,但没有任何运气。作为记录,我在我的装置文件夹中创建了一个名为图像的文件夹,我想在我的测试中使用的两个文件称为 rails.png 和 grid.png)
我试过做以下事情:
it "should be valid" do
image = Image.new :photo => fixture_file_upload('images/rails.png', 'image/png').should be_valid
# I've also tried adding stuff like this
#image.stub!(:has_attached_file).with(:photo).and_return( true )
#image.stub!(:save_attached_files).and_return true
#image.save.should be_true
end
但是 rspec 提示“fixture_file_upload”没有被识别......我打算得到那本 Rspec 书。我在网上四处寻找答案,但似乎找不到任何东西。当我从我的模型中删除验证时,我的测试数据库确实填充了一些数据,所以我知道其中一些工作正常。
提前致谢,
编辑:
images.yml 看起来像这样:
one:
name: MyString
description: MyString
two:
name: MyString
description: MyString
最佳答案
这应该适用于 Rails 2.X:
Image.new :photo => File.new(RAILS_ROOT + '/spec/fixtures/images/rails.png')
从 Rails 3 开始,
RAILS_ROOT
不再使用,您应该使用 Rails.root
.这应该适用于 Rails 3:
Image.new :photo => File.new(Rails.root + 'spec/fixtures/images/rails.png')
一定要买 RSpec 书,太棒了。
关于ruby-on-rails - 使用 Rspec (Rails) 单元测试回形针上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2256012/