简体   繁体   中英

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. 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). Any pointers on how to force and catch the failure of the save or update_attributes methods?

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. The second ( else ) isn't. 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!

save returns false when there's a validation error.

Look at your Project model and produce parameters that are not valid. For example, if there's a validates :some_field, presence: true then skip that field and validation will fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM