【问题标题】:Associations with Factory Girl in Controller specs控制器规格中与 Factory Girl 的关联
【发布时间】:2012-09-25 23:59:29
【问题描述】:

我是 RSpec 的新手,并试图在控制器规范中使用带有关联的 Factory Girl。难点是:

如果我有这样的模型:

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) 根据 a suggestion on this page 将工厂更改为 org_id 未能通过“验证失败:Org 不能为空白”的一些测试

FactoryGirl.define do
  factory :brand do
    org_id 1002
  end
end

2) 使用“symbolize_keys”看起来很有希望。 Herehere 建议使用这样的代码:

(FactoryGirl.build :position).attributes.symbolize_keys 

我不确定如何在我的情况下应用它。下面是一个不起作用的猜测(给出错误 No route matches {:controller=>"brands", :action=>"{:id=>nil, :name=>\"MyString\", :org_id= >1052, :include_in_menu=>false, :created_at=>nil, :updated_at=>nil}"}):

describe BrandsController do
  describe "POST create with valid params" do
    it "creates a new brand" do
      expect {
        post build(:brand).attributes.symbolize_keys 
      }.to change(Brand, :count).by(1)
    end
  end
end

更新

我几乎可以通过 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

所以跟着this question我改成了:

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

哪个有效!

【问题讨论】:

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


    【解决方案1】:

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

    尝试将 expect 块中的代码替换为:

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

    【讨论】:

    • 再次感谢!我得到了这个工作,我将在我的问题中提出一个转折。
    • 太棒了!虽然只是为了让它通过关联 ID 很疯狂。如果有更清洁的方法会很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多