Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.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和Rails在模型中进行测试验证_Ruby On Rails_Ruby_Validation_Rspec_Model - Fatal编程技术网

Ruby on rails 使用RSpec和Rails在模型中进行测试验证

Ruby on rails 使用RSpec和Rails在模型中进行测试验证,ruby-on-rails,ruby,validation,rspec,model,Ruby On Rails,Ruby,Validation,Rspec,Model,我对使用RSpec测试我的应用程序非常陌生,我正在尝试在没有用户的情况下测试注释的有效性,并且不断出现语法错误。 下面是注释模型代码 class注释{order(rating::desc)} 验证:body,presence:true 验证:用户,状态:true 验证:产品,状态:true 验证:额定值,数值性:{only_integer:true} 在创建后提交{CommentUpdateJob.perform\u later(self,user)} 结束 以下是注释规范: require'

我对使用RSpec测试我的应用程序非常陌生,我正在尝试在没有用户的情况下测试注释的有效性,并且不断出现语法错误。 下面是注释模型代码

class注释{order(rating::desc)}
验证:body,presence:true
验证:用户,状态:true
验证:产品,状态:true
验证:额定值,数值性:{only_integer:true}
在创建后提交{CommentUpdateJob.perform\u later(self,user)}
结束
以下是注释规范:

require'rails\u helper'
描述评论做什么
在做之前
@product=product.create!(名称:“赛车”,说明:“快速赛车”)
@user=user.create!(电邮∶jerryhoglen@me.com,密码:“Maggie1!”)
@product.comments.create!(评级:1,用户:@user,body:“糟糕的自行车!”)
结束
它“没有用户无效”
预期(生成(:注释,用户:nil))。无效
结束
结束

你错过了一个
,像这样做:

它“没有用户无效”do
预期(生成(:注释,用户:nil))。无效
结束
但当它失败时,这不是一个非常明确的测试,我建议您检查实际的预期验证错误。 这可能就是它的样子:

expect(ValidatingWidget.new.errors_on(:name)).to include("can't be blank")
expect(ValidatingWidget.new(:name => "liquid nitrogen")).to have(0).errors_on(:name)

请参见

您在这里所做的是好的-构建对象并使用
be\u valid
matcher。但是,如果您使用一条直线来测试模型验证:

describe Comment do
  it { is_expected.to validate_presence_of :user }
end

您可以对其他验证(如唯一性、数字性等)执行此操作,但必须查找语法

/Users/jerryhoglen/.rvm/gems/ruby-2.3.1/gems/activesupport-5.0.0.1/lib/active\u support/dependencies.rb:287:in'load':/Users/jerryhoglen/Desktop/nameofapp/spec/models/comment\u spec.rb:15:语法错误,意外关键字\u end,预期输入结束(SyntaxError)@ZhongZheng.F。。失败:1)注释无效,没有用户失败/错误:expect(build(:Comment,user:nil))。to_not_有效名称错误:未定义方法
build',for##/spec/models/Comment_spec.rb:12:in
block(2级)in'在0.25242秒内完成(加载文件需要2.57秒)9个示例,1失败示例:rspec./spec/models/comment_spec.rb:11#如果没有用户@zhongzheng,comment无效您是否安装了FactoryGirl?尝试
FactoryGirl.build(:comment,user:nil)
1)如果没有用户失败,则注释无效/错误:FactoryGirl.build(:comment,user:nil)ArgumentError:工厂未注册:comment@zhongzheng您需要为注释模型定义工厂。