Ruby on rails 从RSpec示例调用时,未激发\u验证前的ActiveRecord回调

Ruby on rails 从RSpec示例调用时,未激发\u验证前的ActiveRecord回调,ruby-on-rails,ruby,rspec,factory-bot,Ruby On Rails,Ruby,Rspec,Factory Bot,我已经阅读了大多数关于类似问题的答案,但还没有找到解决方案。代码如下: 设置 class Person < ActiveRecord::Base # Other inconsequential code # ... has_and_belongs_to_many :roles before_validation: attach_roles # ... def attach_roles roles << Role.default if roles.

我已经阅读了大多数关于类似问题的答案,但还没有找到解决方案。代码如下:

设置

class Person < ActiveRecord::Base
  # Other inconsequential code
  # ...
  has_and_belongs_to_many :roles
  before_validation: attach_roles
  # ...
  def attach_roles
    roles << Role.default if roles.blank?
  end
end

class Role < ActiveRecord::Base

  has_and_belongs_to_many: people

  def self.default
  #
  # Get default role
  #
  end

end
问题

似乎没有调用
attach\u roles
回调。但是,
应接收
断言为真

在控制台中

p = FactoryGirl.build(:person)
p.roles # []
p.valid? # true
p.roles # [<Role>]
p=FactoryGirl.build(:person)
p、 角色#[]
p、 有效吗真的
p、 角色#[]
有人能解释一下吗

旁注:在尝试创建默认角色时,任何其他想法都是受欢迎的

环境

  • 轨道3.2.1
  • 红宝石1.9.3
  • rspec2.12.0
  • 工厂女孩4.1.0

你的
应该收到
测试证明
附加角色被调用,只是没有达到你的预期

我看到两件事与我有关

其中一点与@apneadiving指出的相同


在Ruby中尝试分配实例变量时,必须使用
self.roles
。我不确定的是如何
no。不起作用。你提出这个建议有什么具体的原因吗?因为只要
角色
就可以用作访问者;保存
不在字段右侧保存“foo”。但我不在乎坚持。它似乎在控制台中按预期工作。
p = FactoryGirl.build(:person)
p.roles # []
p.valid? # true
p.roles # [<Role>]
def attach_roles
  roles.build(Role.default)
end