Rails alias_attribute在RSPEC中不起作用

问题描述 投票:0回答:1

在商店模型:

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创纪录吗?

请注意,这适用于开发||生产环境,只在测试中出错。

谢谢。

ruby-on-rails ruby rspec factory-bot rspec-rails
1个回答
0
投票

在只有一个属性,一个别名和具有相同默认值的工厂的基本模型上,我没有得到这种行为(使用RSpec,Factory Girl,Rails 5.1)。提供工厂的其余部分和模型将有所帮助。

要找到错误的起源,您可以:

  1. 评论除alias_attribute之外的整个Shop模型
  2. 评论除basic_token以外的整个工厂
  3. 检查一下只做create(:shop)的虚拟测试
  4. 逐批取消注释注释行,每次迭代运行测试。

如果上面的步骤3失败:5。尝试更改别名的名称,查看应用程序中的任何内容是否与名称token冲突6.尽可能尝试git bisect以查找有罪提交。希望有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.