【问题标题】:How to create factories for models with nested_attributes in Factorybot如何在 Factorybot 中为具有nested_attributes 的模型创建工厂
【发布时间】:2019-10-10 01:40:34
【问题描述】:

我想用 RSpec 测试以下控制器

coupons_controller.rb:

class Api::V1::CouponsController < ApiController
  def index
    if params[:profile_id]
      @coupons = Profile.find(params[:profile_id]).coupons
    end
  end
end

我想知道

1) 如何用FactoryBot创建工厂(spec/factories/profiles.rb, coupons.rb, coupon_profiles.rb)

2)spec/controllers/coupons_controllers.rb的写法:

关联

profile.rb

class Profile < ApplicationRecord
  accepts_nested_attributes_for :coupon_profiles
end

优惠券.rb

class Coupon < ApplicationRecord
  has_many :coupon_profiles
end

coupon_profile.rb

class CouponProfile < ApplicationRecord
  belongs_to :coupon
  belongs_to :profile
end

【问题讨论】:

    标签: ruby rspec associations nested-attributes


    【解决方案1】:

    类似:

    factory :profile, class: 'Profile', do
      ...
    end
    factory :coupon, class: 'Coupon' do 
      ...
    end
    factory :coupon_profile, class: 'CouponProfile' do
      coupon
      profile
    end
    

    老实说,最好的办法是查看FactoryBot 的 GETTING_STARTED 自述文件——您想知道的所有内容都在其中,并附有示例。

    对于您的控制器规格,您是否查看过Rspec Controller Specs Documentation?您应该能够执行以下操作:

    describe 'CouponsController' do 
      subject(:request) { '/index', params: params }
    
      shared_examples_for 'success' do
        it do
          request
          expect(response).to have_http_status(:success)
        end
      end
    
      describe '#index' do
        context 'empty params' do
          let(:params) { {} }
    
          it_behaves_like 'success'
        end
    
        context 'profile_id present' do
          let(:params)         { { profile_id: profile.id } }
          let!(:profile)       { coupon_profile.profile }
          let(:coupon_profile) { create :coupon_profile }
    
          it_behaves_like 'success'
        end 
      end
    end
    

    【讨论】:

    • 你就是那个女人!使用class 是我对内部类的追求,例如Coupon::Profile。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多