【问题标题】:how testing associated model?如何测试关联模型?
【发布时间】:2015-08-31 07:39:03
【问题描述】:

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

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 文档

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

失败:

1) 相册有一个有效的工厂 失败/错误:Factory.create(:album).should be_valid 名称错误: 未初始化的常量工厂 # ./spec/models/album_spec.rb:5:in `block (2 levels) in '

在 0.96458 秒内完成(加载文件需要 2.34 秒)1 例如,1 次失败

失败的例子:

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

【问题讨论】:

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


    【解决方案1】:

    你试过了吗:

    FactoryGirl.create(:album).should be_valid
    

    ...而不是:

    Factory.create(:album).should be_valid
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多