Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 3 铁路Rspec&;工厂女工考试协会_Ruby On Rails 3_Rspec_Tdd - Fatal编程技术网

Ruby on rails 3 铁路Rspec&;工厂女工考试协会

Ruby on rails 3 铁路Rspec&;工厂女工考试协会,ruby-on-rails-3,rspec,tdd,Ruby On Rails 3,Rspec,Tdd,我必须在模型中接受嵌套属性。我想建立一个测试,以确保嵌套属性不能为空等,我真的不明白我如何可以做测试 我的两个简单模型: # SeoMapping Model class SeoMapping < ActiveRecord::Base belongs_to :mappingtable, :polymorphic => true attr_accessible :seo_url validates :seo_url, :presence => true, :uniqu

我必须在模型中接受嵌套属性。我想建立一个测试,以确保嵌套属性不能为空等,我真的不明白我如何可以做测试

我的两个简单模型:

# SeoMapping Model
class SeoMapping < ActiveRecord::Base
  belongs_to :mappingtable, :polymorphic => true
  attr_accessible :seo_url
  validates :seo_url, :presence => true, :uniqueness => true   
end

# Page Model
class Page < ActiveRecord::Base
  has_one :seo_mappings, :as => :mappingtable, :dependent => :destroy
  accepts_nested_attributes_for :seo_mappings 
  attr_accessible :content, :h1, :meta_description, :title, :seo_mappings_attributes
  .........
end
还有我的测试:

require 'spec_helper'

describe Page do
  it "has a valid factory" do
    expect(create(:page)).to be_valid
  end

  # Cant get this spec to work?
  it "it is invalid without a seo_url" do
    page = build(:page)
    seo_mapping = build(:seo_mapping, seo_url: nil)
    page.seo_mapping.should_not be_valid
    # expect(build(:page, :seo_mapping_attributes[:seo_url] => nil)).to_not be_valid
  end

  it "is invalid without a title" do
    expect(build(:page, title: nil)).to_not be_valid
  end
  ...............
end

通常,对于这类事情,我会使用一种叫做宝石的宝石。它允许您简单地断言您的模型验证特定属性的存在

it { should validate_presence_of(:seo_url) }
it { should validate_uniqueness_of(:seo_url) }
如果您不想使用gem,请尝试以下方法:

seo_mapping = build(:seo_mapping, seo_url: nil)
page = build(:page, seo_mapping: seo_mapping)
page.should_not be_valid

我喜欢这颗宝石。但是如果我尝试它{应该验证(:seo_url)的存在}我会得到错误“未定义的方法`seo_url=”,在我看来,它不喜欢一个模型上的关联验证?
seo_mapping = build(:seo_mapping, seo_url: nil)
page = build(:page, seo_mapping: seo_mapping)
page.should_not be_valid