![](/img/trans.png)
[英]How do I authenticate a user if they are not using my web (rails) application, e.g. using an API
[英]How do I test for failure of (e.g.) @project.save in my controller using minitest in Rails?
我正在努力提高我的测试覆盖率(刚刚安装了simplecov)并且非常高兴能够获得良好的覆盖率。 但是,我没有在我的测试中捕获一些失败模式,但我不知道如何强制失败,例如,在Rails中创建对象期间的保存(5.2,如果这很重要)。 有关如何强制并捕获save
或update_attributes
方法失败的任何指针?
我的主要测试工作正常。 我不知道如何在测试中强制执行这些分支的代码!
相关控制器方法:
def create
@project = current_user.projects.build(project_params)
if @project.save
flash[:notice] = "Project created!"
redirect_to user_path(current_user)
else
flash[:alert] = "There was an error. Your project was not created."
render 'new'
end
end
测试该测试的第一个分支( if @project.save
)。 第二个( else
)不是。 我用来测试成功的测试如下:
sign_in @user
assert_difference 'Project.count', 1 do
post projects_path, params: {project: {name: @new_project_name, user_id: @user.id}}
end
assert_redirected_to user_path(@user)
我真正喜欢的是我能成功assert_no_difference
东西!
当出现验证错误时, save
返回false
。
查看您的Project
模型并生成无效的参数。 例如,如果有一个validates :some_field, presence: true
则跳过该字段,验证将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.