【问题标题】:Testing Controller create action with belongs_to association测试控制器创建操作与 belongs_to 关联
【发布时间】:2013-12-07 02:09:10
【问题描述】:

您如何测试具有所需的 belongs_to 关联的控制器创建操作? 如果我删除 validates :address, presence: true 它可以工作,但这个验证是必要的。

models/accreditor.rb

class Accreditor < ActiveRecord::Base
  belongs_to :address, dependent: :destroy
  validates :address, presence: true

spec/controllers/accreditors_controller_spec.rb

describe AccreditorsController do
  describe 'POST #create' do
    it 'saves the new accreditor in the database' do
      address = FactoryGirl.create(:address)
      accreditor = FactoryGirl.build(:accreditor, address: address)
      expect{
        post :create, accreditor: accreditor.attributes
      }.to change(Accreditor, :count).by(1)
    end
  end

此外,accreditor 和 address factory 适用于所有其他控制器操作。

【问题讨论】:

    标签: ruby-on-rails factory-bot rspec2


    【解决方案1】:

    如果您进行此更改:

    accreditor = FactoryGirl.build(:accreditor, address_id: address.id)
    

    它应该可以工作。

    但是你不应该在这里使用工厂,你应该直接在那里放置参数,因为这是发布表单的人会做的事情。

    【讨论】:

    • 不幸的是,这个解决方案不起作用。它创建与FactoryGirl.build(:accreditor, address: address) 相同的属性哈希
    【解决方案2】:

    这似乎是最好的解决方案。

    describe 'POST #create' do
      it 'saves the new accreditor in the database' do
        expect{
          post :create, accreditor: FactoryGirl.attributes_for(:accreditor,
              address_attributes: FactoryGirl.attributes_for(:address))
        }.to change(Accreditor, :count).by(1)
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 2017-11-29
      相关资源
      最近更新 更多