Ruby on rails 控制器规范中与Factory Girl的关联

Ruby on rails 控制器规范中与Factory Girl的关联,ruby-on-rails,rspec,factory-bot,Ruby On Rails,Rspec,Factory Bot,我是RSpec的新手,我试图通过使用Factory Girl了解控制器规格中的关联。困难在于: 在功能测试中有必要使用“attributes_for” “”的属性 如果我有这样的模型: class Brand < ActiveRecord::Base belongs_to :org validates :org, :presence => true end class Org < ActiveRecord::Base has_many :brands

我是RSpec的新手,我试图通过使用Factory Girl了解控制器规格中的关联。困难在于:

  • 在功能测试中有必要使用“attributes_for”
  • “”的属性
如果我有这样的模型:

class Brand < ActiveRecord::Base
  belongs_to :org    
  validates :org, :presence => true
end

class Org < ActiveRecord::Base
  has_many :brands
end
FactoryGirl.define do
  factory :brand do
    association :org
  end
end
此控制器规范失败:

describe BrandsController do
  describe "POST create with valid params" do
    it "creates a new brand" do
      expect {
        post :create, brand: attributes_for(:brand)
      }.to change(Brand, :count).by(1)
    end
  end
end
(如果我注释掉“validates:org,:presence=>true”,它就会通过)

我们提出了许多解决方案,我认为我一直在犯一些简单的错误,这意味着我无法让它们中的任何一个发挥作用

1) 将工厂更改为org_id per失败了许多测试,并显示“验证失败:组织不能为空”

2) 使用“符号化_键”看起来很有希望。建议使用如下代码:

(FactoryGirl.build :position).attributes.symbolize_keys 
我不知道如何将这一点应用到我的案例中。下面是一个不起作用的猜测(给出错误No route matches{:controller=>“brands”,“action=>”{:id=>nil,:name=>\“MyString\”,:org\u id=>1052,:include\u in\u menu=>false,:created\u at=>nil,:updated\u at=>nil}):

更新

我几乎用Shioyama下面的答案得到了这个结果,但得到了错误信息:

Failure/Error: post :create, brand: build(:brand).attributes.symbolize_keys
ActiveModel::MassAssignmentSecurity::Error:
  Can't mass-assign protected attributes: id, created_at, updated_at
下面我把它改成:

post :create, brand: build(:brand).attributes.symbolize_keys.reject { |key, value| !Brand.attr_accessible[:default].collect { |attribute| attribute.to_sym }.include?(key) }
真管用

在解决方案2中),您没有将操作传递给
post
,这就是它抛出错误的原因

尝试替换该
块中的代码,以期:

post :create, brand: build(:brand).attributes.symbolize_keys

再次感谢!我将在我的问题中加入一个转折点来解决这个问题。太好了!为了让它通过协会id,疯狂了很久。如果有更干净的方法,那就太好了。
post :create, brand: build(:brand).attributes.symbolize_keys.reject { |key, value| !Brand.attr_accessible[:default].collect { |attribute| attribute.to_sym }.include?(key) }
post :create, brand: build(:brand).attributes.symbolize_keys