如何测试相关模型?

时间:2015-08-31 07:39:04

标签: ruby-on-rails ruby-on-rails-4 rspec rspec2

请帮助解决问题。我有相关的模型:

class Album < ActiveRecord::Base
  validates :title, presence: true, length: { maximum:  50, minimum: 3 }, uniqueness: { case_sensitive: false }
  validates :description, presence: true, length: { maximum:  600, minimum: 10 }

  belongs_to :user
  has_many :images
end

class Status < ActiveRecord::Base
  has_many :users
end


class User < ActiveRecord::Base
  belongs_to :status
  has_many :albums, dependent: :destroy

  validates :name, presence: true
  validates :email, presence: true

  has_attached_file   :avatar, 
                      :styles => { 
                                    :large => "300x300>", 
                                    :medium => "100x100>", 
                                    :thumb => "30x30>" 
                      }, 
                      :default_url => "no_user_ava_3.png"

  validates_attachment_content_type :avatar, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]
  validates_attachment_file_name :avatar, :matches => [/png\Z/, /jpe?g\Z/, /gif\Z/]  
end

我正在尝试为模型编写测试。我创建了跟随工厂:

FactoryGirl.define do
  factory :status do
    sequence(:id){ |id| id }
    title 'user'
  end
end

FactoryGirl.define do
  factory :user do
    sequence(:name){ |i| "us#{i}" }
    sequence(:email){ |i| "us#{i}@ad.ad" }
    password 'qwerty'
    password_confirmation{ |u| u.password } 
    association :status 
  end 
end

FactoryGirl.define do
  factory :album do
    sequence(:title){ |i| "title#{i}" }
    association :user 
    closed nil
    description 'The behavior of or the parent object.'
  end
end

我的模特测试:

require 'spec_helper'

describe Album do
  it "has a valid factory" do
    Factory.create(:album).should be_valid
  end
end

在我进行测试后,我得到以下内容:

  

kalinin @ kalinin~ / rails / phs $ rspec spec / models --format documentation

     

相册有一个有效的工厂(FAILED - 1)

     

故障:

     

1)相册有一个有效的工厂        失败/错误:Factory.create(:album)。应该是be_valid        NameError:          未初始化的恒定工厂        #./spec/models/album_spec.rb:5:在'块(2级)中&#39;

     

以0.96458秒结束(文件加载时间为2.34秒)1   例如,1次失败

     

失败的例子:

     

rspec ./spec/models/album_spec.rb:4#相册有一个有效的工厂

1 个答案:

答案 0 :(得分:1)

你试过了吗?

FactoryGirl.create(:album).should be_valid

...而不是:

Factory.create(:album).should be_valid