在商店模型:
class Shop < ActiveRecord::Base
alias_attribute :token, :basic_token
# basic_token column is set NOT to be NULL in DB
end
在工厂工厂:
FactoryGirl.define do
factory :shop do
basic_token '12313123123123123123123'
...
...
end
end
在RSPEC商店控制器中:
require 'rails_helper'
RSpec.describe ShopsController, type: :controller do
before do
@shop = create(:shop) # FAILS
=> Failure/Error: @shop = create(:shop)
=> ActiveRecord::StatementInvalid:
=> PG::NotNullViolation: ERROR: null value in column "basic_token" violates not-null constraint
end
describe "" do
........
end
end
Rails控制台测试:
WITH alias_attribute:
(byebug) @shop = build(:shop)
#<Shop remote_id: 1110212666, domain: "abc.myshopify.com", basic_token: nil, created_at: nil, updated_at: nil, ... >
(byebug) @shop.valid?
true
(byebug) @shop.errors.messages
{}
WITH alias_attribute commented (# alias_attribute :token, :basic_token):
(byebug) @shop = build(:shop)
#<Shop remote_id: 1110212666, domain: "abc.myshopify.com", basic_token: "12313123123123123123123", created_at: nil, updated_at: nil, ... >
(byebug) @shop.valid?
true
(byebug) @shop.errors.messages
{}
评论alias_attribute :token, :basic_token
,它的确有效。
知道为什么我不能用alias_attribute
创纪录吗?
请注意,这适用于开发||生产环境,只在测试中出错。
谢谢。
在只有一个属性,一个别名和具有相同默认值的工厂的基本模型上,我没有得到这种行为(使用RSpec,Factory Girl,Rails 5.1)。提供工厂的其余部分和模型将有所帮助。
要找到错误的起源,您可以:
alias_attribute
之外的整个Shop模型basic_token
以外的整个工厂create(:shop)
的虚拟测试如果上面的步骤3失败:5。尝试更改别名的名称,查看应用程序中的任何内容是否与名称token
冲突6.尽可能尝试git bisect
以查找有罪提交。希望有所帮助。