我已经阅读了与类似问题有关的大部分答案,但尚未找到解决方案。代码如下:
设置
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
测试
require 'spec_helper'
RSpec.configure do |config|
config.include FactoryGirl::Syntax::Methods
end
describe Person do
context "constructor" do
it "creates a valid Person" do
person = build(:person)
person.should_receive(:attach_roles) # This works
person.valid?
puts person.roles.inspect # Returns []
end
it "creates a another valid Person" do
person = build(:person)
person.valid?
person.should be_valid # This fails
puts person.roles.inspect # Returns []
end
end
end
问题
attach_roles
回调似乎没有被调用。然而should_receive
断言为真
在控制台中
p = FactoryGirl.build(:person)
p.roles # []
p.valid? # true
p.roles # [<Role>]
有人能解释一下吗?
旁注:也欢迎尝试创建默认角色的任何其他想法。
环境:
- 导轨3.2.1
- 红宝石1.9.3
- rspec 2.12.0
- factory_girl 4.1.0