0

我有这个模型:

class Proceeding < ActiveRecord::Base
  attr_accessible :archive_id, :assets, :kind
  validates_presence_of :archive_id, :kind
  validates_format_of :kind, :with => /^(deroga|progetto)$/
  validate :assets_list_must_be_valid_or_empty

  def assets_list
    self.assets.split.map!{|a| a.upcase.strip}
  end

  private
  def assets_list_must_be_valid_or_empty
    if self.assets
      al = self.assets_list
      if Asset.find_all_by_name(al).size < al.size
        errors.add(:assets, "list is not valid")
      end
    end
  end
end

这个规格:

require 'spec_helper'
describe Proceeding do
  before :each do
    @proceeding = Proceeding.new( archive_id: "test", kind: "progetto", assets: "")
  end

  it "is valid" do
    expect(@proceeding).to be_valid   #S1
  end

  it "single is valid" do
    @proceeding.assets = " 1.1.c  "
    expect(@proceeding).to be_valid   #S2
  end

  it "multiple is valid" do
    @proceeding.assets = " 1.1.c  80.1.a 2.1.B 4.1.b  "
    expect(@proceeding).to be_valid   #S3
  end
end

S1 有效;S2 和 S3 不起作用:

Failures:

1) Proceeding asset multiple is valid
   Failure/Error: expect(@proceeding).to be_valid
   expected #<Proceeding id: nil, kind: "progetto", archive_id: "test", assets: "     
   1.1.c  80.1.a 2.1.B 4.1.b  ", created_at: nil, updated_at: nil> to be valid, but 
   got errors: Assets list is not valid # ./spec/models/proceeding_spec.rb:62:in 
   `block (3 levels) in <top (required)>'

2) Proceeding asset single is valid
   Failure/Error: expect(@proceeding).to be_valid
   expected #<Proceeding id: nil, kind: "progetto", archive_id: "test", assets: "  
   1.1.c  ", created_at: nil, updated_at: nil> to be valid, but got errors: Assets 
   list is not valid # ./spec/models/proceeding_spec.rb:57:in `block (3 levels) in 
   <top (required)>'

rspec ./spec/models/proceeding_spec.rb:60 # Proceeding asset multiple is valid
rspec ./spec/models/proceeding_spec.rb:55 # Proceeding asset single is valid

但是,这两个示例适用于控制台和 http。基于助手预定义验证器的规范可以正常工作。

如何修复这些规格?

谢谢

4

1 回答 1

0

我更改了样本 S2 和 S3,所以:

it "single is valid" do
  @proceeding.assets = " 1.1.c  "
  @proceeding.save
  expect(@proceeding.assets_list.count).to eq(1)   #S2
end

it "multiple is valid" do
  @proceeding.assets = " 1.1.c  80.1.A 4.1.b  "
  @proceeding.save
  expect(@proceeding.assets_list.count).to eq(3)   #S3
end

现在它起作用了。

于 2013-05-24T18:42:43.290 回答