[英]How do I test for failure of (e.g.) @project.save in my controller using minitest in Rails?
I'm trying to improve my test coverage (just installed simplecov) and was quite pleased to have good coverage already. 我正在努力提高我的测试覆盖率(刚刚安装了simplecov)并且非常高兴能够获得良好的覆盖率。 However, I wasn't catching some failure modes in my tests, but I don't know how to force the failure of, for example, a save during creation of an object in Rails (5.2, if that matters). 但是,我没有在我的测试中捕获一些失败模式,但我不知道如何强制失败,例如,在Rails中创建对象期间的保存(5.2,如果这很重要)。 Any pointers on how to force and catch the failure of the save
or update_attributes
methods? 有关如何强制并捕获save
或update_attributes
方法失败的任何指针?
My main tests are working fine. 我的主要测试工作正常。 I've just got no idea how to force the code down these branches in a test! 我不知道如何在测试中强制执行这些分支的代码!
The relevant controller method: 相关控制器方法:
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
The first branch of this test ( if @project.save
) is tested. 测试该测试的第一个分支( if @project.save
)。 The second ( else
) isn't. 第二个( else
)不是。 The test that I'm using to test success is as follows: 我用来测试成功的测试如下:
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)
What I'd really like is something where I can assert_no_difference
successfully! 我真正喜欢的是我能成功assert_no_difference
东西!
save
returns false
when there's a validation error. 当出现验证错误时, save
返回false
。
Look at your Project
model and produce parameters that are not valid. 查看您的Project
模型并生成无效的参数。 For example, if there's a validates :some_field, presence: true
then skip that field and validation will fail. 例如,如果有一个validates :some_field, presence: true
则跳过该字段,验证将失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.