我已經閱讀了大多數有關類似問題的答案,但還沒有找到解決方案。代碼如下:從RSpec調用時未激發ActiveRecord before_validation回調示例
設置
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
嘗試:'self.roles <<' – apneadiving
沒有。不起作用。你有這個建議的具體原因嗎?因爲只有角色可以用作訪問者。 –
出於同樣的原因'field_name ='foo'; save'不會在字段中保存'foo' – apneadiving