【问题标题】:FactoryGirl + Mongoid + RSpec not properly constructing objects.FactoryGirl + Mongoid + RSpec 没有正确构造对象。
【发布时间】:2013-07-02 04:03:22
【问题描述】:

我正在尝试在我的应用程序中设置测试,但在使用 RSpec、FactoryGirl 和 Mongoid 时遇到了问题。我有以下工厂:

FactoryGirl.define do
  factory :user do |u|
    u.name             { Faker::Name.name }
    u.email            { Faker::Internet.email }
    u.crypted_password { Faker::Lorem.characters(10) }
    u.password_salt    { Faker::Lorem.characters(10) }
    u.role             :user
  end
end

我尝试在我的测试中使用这个工厂:

require 'spec_helper'
describe User do
  it "has a valid factory" do
    create(:user).should be_valid
  end
end

但我收到此错误:

  1) User has a valid factory
     Failure/Error: FactoryGirl.create(:user).should be_valid
     NoMethodError:
       undefined method `user' for #<User:0x007ff24a119b28>
     # ./spec/models/user_spec.rb:5:in `block (2 levels) in <top (required)>'

我不知道是什么导致了这个错误。另外,有没有办法使用 rspec 查看完整的堆栈跟踪?

【问题讨论】:

    标签: ruby-on-rails rspec mongoid factory-bot


    【解决方案1】:

    这条线有问题

    u.role :user
    

    我猜您想将默认角色定义为“用户”?然后不要使用符号或方法,而是使用字符串

    u.role 'user'
    

    【讨论】:

    • @Max,我不知道你是怎么定义角色的,但是你可以在控制台中使用@user.role = something进行验证。任何在控制台中工作的东西都可以在工厂工作。
    • 我发现了问题。这是一个简单的错字。我正在验证字段 user 而不是字段 role。你知道如何从 rspec 获取完整的堆栈跟踪吗?如果我能够查看堆栈跟踪,我可能会更早注意到。
    • @Max,只要在你的rspec命令中加上-b参数,就是回溯。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 2018-07-05
    相关资源
    最近更新 更多