Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RSpec检查数据库字段具有特定字符串_Ruby On Rails_Rspec - Fatal编程技术网

Ruby on rails RSpec检查数据库字段具有特定字符串

Ruby on rails RSpec检查数据库字段具有特定字符串,ruby-on-rails,rspec,Ruby On Rails,Rspec,我试图确保在创建用户时,“度量单位”字段的默认字符串为英制。当我通过创建一个用户进行测试时,我得到了期望的结果,但是当我使用我的规范进行测试时,我得到了'got:nil' 知道我在规范中做错了什么吗 require 'spec_helper' require 'cancan/matchers' describe User do subject(:user) { User.new(email: 'test@test.com', password: '12345678', goal_id:

我试图确保在创建用户时,“度量单位”字段的默认字符串为英制。当我通过创建一个用户进行测试时,我得到了期望的结果,但是当我使用我的规范进行测试时,我得到了'got:nil'

知道我在规范中做错了什么吗

require 'spec_helper'
require 'cancan/matchers'

describe User do
    subject(:user) { User.new(email: 'test@test.com', password: '12345678', goal_id: '1', experience_level_id: '1', gender: 'female') }

  it "should be assigned measurement_units of imperial" do
    user.measurement_units.should eq("imperial") 
  end
end
上述测试返回:

1) User should be assigned measurement_units of imperial
     Failure/Error: user.measurement_units.should eq("imperial")

       expected: "imperial"
            got: nil

       (compared using ==)
     # ./spec/models/user_spec.rb:20:in `block (2 levels) in <top (required)>'
1)应为用户指定英制的测量单位
故障/错误:user.measurement\u units.should eq(“英制”)
预期:“帝国”
得:零
(使用==进行比较)
#./spec/models/user_spec.rb:20:in'block(2层)in'
我知道这可能是最基本的,但我想不出来

编辑:

我在用户模型上的创建前过滤器中指定初始测量单位,如下所示:

class User < ActiveRecord::Base

before_create :assign_initial_settings

def assign_initial_settings
  self.measurement_units = "imperial"
end
class用户
您的回调在\u create之前是一个
,但您在测试中没有实际调用User.create-因此您的回调没有运行


如果用
create
替换
new
,您应该会看到您期望的行为。

设置默认度量单位的代码在哪里?刚刚更新了问题,说明我如何设置度量单位,这会导致我的所有测试失败,并出现以下情况:
RuntimeError:Called id for nil,这将被误认为是4——如果您真的想要nil的id,请使用object\u id
我猜这是因为记录验证失败——可能您需要一个
密码\u确认
。试试
#创建而不是
#创建
,你肯定会知道的。我现在正在努力克服那个错误。谢谢你的建议。我会向你汇报的,你说的一切都是对的。谢谢你的帮助!非常感谢!