0

我一直在实现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)>'

工厂.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

项目.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 很陌生,非常感谢任何帮助!

4

2 回答 2

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

现在您可以检查您的测试对象以找出验证失败的原因。

于 2013-01-04T04:20:41.777 回答
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
于 2013-01-07T13:29:44.637 回答