FactoryGirl - 使用没有给出期望结果的特征

时间:2015-09-19 09:35:22

标签: ruby-on-rails-4 factory-bot

当我以这种方式定义用户工厂时

  FactoryGirl.define do
    factory :user do
      roles {[FactoryGirl.create(:role, :system, :admin)]}
      email "visitor.administration@example.com"
      name  "Visitor Administration"
      password "visitor123"
    end
  end

使用以下角色工厂:

    FactoryGirl.define do
      factory :role do
        company "internal"
        group "administration"
        function "visitor"
        activities '{}'
      end
      trait :system do
        group "system"
      end
      trait :admin do
        function "admin"
        activities '{"sheet" => ["create", "update", "delete", "show", "index"] }'
      end  
    end
执行

FactoryGirl.create(:user)

给了我预期的结果......

但是如果我尝试在用户工厂中定义特征

  FactoryGirl.define do
    factory :user do
      roles {[FactoryGirl.create(:role)]}
      email "visitor.administration@example.com"
      name  "Visitor Administration"
      password "visitor123"

      trait :system_admin do
        roles {[FactoryGirl.create(:role, :system, :admin)]}
        email "admin.system@example.com"
        name  "Admin System"
        password "admin123"
      end
      factory :system_admin_user,  traits: [:system_admin ] 
    end
  end

我现在执行:

user = FactoryGirl.create(:system_admin_user)

然后我收到错误:

    (0.3ms)  BEGIN
      SQL (5.4ms)  INSERT INTO "roles" ("group", "function", "activities", "created_at", "updated_at") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["group", "system"], ["function", "admin"], ["activities", nil], ["created_at", "2015-09-19 09:08:19.572605"], ["updated_at", "2015-09-19 09:08:19.572605"]]
    PG::NotNullViolation: ERROR:  null value in column "activities" violates not-null constraint
    DETAIL:  Failing row contains (14, internal, system, admin, null, 2015-09-19 09:08:19.572605, 2015-09-19 09:08:19.572605).

活动JSON字段是否未正确定义?

1 个答案:

答案 0 :(得分:0)

是的,活动属性编写不正确:

activities '{"sheet" => ["create", "update", "delete", "show", "index"] }'

应该是:

活动{{sheet:[“create”,“update”,“delete”,“show”,“index”]}}