测试载波持续返回“图像不能为空” - 错误

时间:2013-01-03 19:17:42

标签: ruby-on-rails rspec factory-bot carrierwave

我一直在实施carrierwave,它在浏览器中运行良好。但是,我的测试不断回复:

错误

  1) Item 
     Failure/Error: it { should be_valid }
       expected valid? to return true, got false
     # ./spec/models/item_spec.rb:36:in `block (2 levels) in <top (required)>'

factories.rb

include ActionDispatch::TestProcess

FactoryGirl.define do

  sequence(:email) { |n| "User#{n}@example.com"}

  factory :user do
    name     "John doe"
    email
    password "foobar"
    password_confirmation "foobar"
  end

  factory :list do
    name "Lorem ipsum"
    user
  end

  factory :item do
    image { fixture_file_upload(Rails.root.join('spec', 'support', 'test_images', 'google.png'), 'image/png') }
    title "Shirt"
    link "www.example.com"
    list
  end
end

item_spec.rb

require 'spec_helper'

describe Item do

  let(:user) { FactoryGirl.create(:user) }
    let(:list) { FactoryGirl.create(:list) }

  before do
    @item = list.items.build(title: "Lorem ipsum")
    @item.valid?
    puts @item.errors.full_messages.join("\n")
  end

  subject { @item }

  it { should respond_to(:title) }
  it { should respond_to(:list_id) }
  it { should respond_to(:list) }
  it { should respond_to(:image) }
  it { should respond_to(:remote_image_url) }
  its(:list) { should == list }

  it { should be_valid }

  describe "when list_id not present" do
    before { @item.list_id = nil }
    it { should_not be_valid }
  end

  describe "when image not present" do
    before { @item.image = "" }
    it { should_not be_valid }
  end

  describe "with blank title" do
    before { @item.title = " " }
    it { should_not be_valid }
  end

  describe "with title that is too long" do
    before { @item.title = "a" * 141 }
    it { should_not be_valid }
  end
end

item.rb的

class Item < ActiveRecord::Base
  attr_accessible :link, :list_id, :title, :image, :remote_image_url
  belongs_to :list
  mount_uploader :image, ImageUploader

  validates :title, presence: true, length: { maximum: 140 }
  validates :list_id, presence: true
  validates_presence_of :image
end

我在spec / support / test_images文件夹中有一个名为google.png的图片。

我对rails非常陌生,因此非常感谢任何帮助!

2 个答案:

答案 0 :(得分:0)

it { should be_valid }

失败,因为(正如您所料)主题无效。你需要找出为什么它是无效的。尝试这样的事情:

it "should be valid" do
  subject.valid?
  subject.errors.should be_empty
end

现在示例将失败,但错误消息将更具描述性。

另一种方法是将pry添加到您的项目中。然后将binding.pry添加到您要打开控制台的位置:

it "should be valid" do
  subject.valid?
  binding.pry
  subject.errors.should be_empty
end

现在,您可以检查测试对象,以确定验证失败的方式。

答案 1 :(得分:0)

我觉得很蠢。忘了附加图像,这显然导致验证失败。

不得不改变:

 before do
    @item = list.items.build(title: "Lorem ipsum")
    @item.valid?
    puts @item.errors.full_messages.join("\n")
 end

要:

  before do
    @item = list.items.build(title: "Lorem ipsum")
    @item.image = fixture_file_upload('/test_images/google.png', 'image/png')
  end