Rspec 与工厂女孩和basic的测试有很多关系

Rspec 与工厂女孩和basic的测试有很多关系,rspec,sql,ruby-on-rails,factory-bot,Rspec,Sql,Ruby On Rails,Factory Bot,我一直在关注这个问题,我在这里找到了这个问题的解决方案 这是两种模式: class Admin::Post < ActiveRecord::Base has_many :sml, :class_name => "Admin::PostSml", :dependent => :destroy accepts_nested_attributes_for :sml, allow_destroy: true, reject_if: proc { |sml| sml[:fkl

我一直在关注这个问题,我在这里找到了这个问题的解决方案

这是两种模式:

class Admin::Post < ActiveRecord::Base
  has_many :sml, :class_name => "Admin::PostSml", :dependent => :destroy
    accepts_nested_attributes_for :sml, allow_destroy: true, reject_if: proc { |sml| sml[:fklang].blank? }
end

class Admin::PostSml < ActiveRecord::Base
  belongs_to :post
end
以及相应的模型试验:

require 'spec_helper'

describe Admin::Post do
  it "should create post and sml for post" do
    post = FactoryGirl.create(:post_sml)

    post.should be_valid
  end
end
但如果我这样测试,就会出现错误:

Admin::Post should create post and sml for post
 Failure/Error: post = FactoryGirl.create(:post_sml)
 NoMethodError:
   undefined method `admin_post=' for #<Admin::PostSml:0x007ffbfe7345e0>
 # ./spec/factories/admin_posts.rb:10:in `block (4 levels) in <top (required)>'
 # ./spec/models/admin/post_spec.rb:5:in `block (2 levels) in <top (required)>'

你应该使用特征,而不是筑巢工厂。您可以指定Post的一个特征,用它创建PostSml

FactoryGirl.define do
  factory :admin_post, :class => 'Admin::Post' do
    f_del 0
    published 1

    trait :with_sml do
      after(:create) do |admin_post|
        create(:admin_post_sml, post: admin_post)
      end
    end
  end

  factory :admin_post_sml, :class => 'Admin::PostSml' do
    fklang "it"
    title Faker::Lorem.sentence
    abstract Faker::Lorem.sentence
    description Faker::Lorem.paragraph
    pub_date "2014-02-04 09:43:43"
    exp_date "2014-02-04 09:43:43"
  end
end

然后你可以这样使用:
create(:admin\u post,:with\u sml)
create(:admin\u post\u sml,post:post)
如果我这样做,我得到的是未初始化的常量post,可能是因为我得到了admin::post作为模型,而不仅仅是post
工厂:post\u sml
这是无效的工厂,它指的是
PostSml
FactoryGirl.define do
  factory :admin_post, :class => 'Admin::Post' do
    f_del 0
    published 1

    factory :post_with_sml do
      after(:create) do |admin_post|
        create(:admin_post_sml, post: admin_post)
      end
    end
  end

  factory :admin_post_sml, :class => 'Admin::PostSml' do
    fklang "it"
    title Faker::Lorem.sentence
    abstract Faker::Lorem.sentence
    description Faker::Lorem.paragraph
    pub_date "2014-02-04 09:43:43"
    exp_date "2014-02-04 09:43:43"
  end

end
FactoryGirl.define do
  factory :admin_post, :class => 'Admin::Post' do
    f_del 0
    published 1

    trait :with_sml do
      after(:create) do |admin_post|
        create(:admin_post_sml, post: admin_post)
      end
    end
  end

  factory :admin_post_sml, :class => 'Admin::PostSml' do
    fklang "it"
    title Faker::Lorem.sentence
    abstract Faker::Lorem.sentence
    description Faker::Lorem.paragraph
    pub_date "2014-02-04 09:43:43"
    exp_date "2014-02-04 09:43:43"
  end
end