简体   繁体   中英

RSpec - How to test the if-else block in update method of controller

Let's say I have a database to store the data of people (name, email). And there's an update method in the controller. The method is like:

  def update
    @people = People.find(params[:id])
    if @people.update(people_params)
       redirect_to people_path
    else
       render 'edit'
    end
  end

I wonder how can I test the situation that the update failed? Or do I really need to test it? I have searched it on StackOverflow, there is a link about it, but it not says if I should or should not to test it. Could anyone give me some help about it? If it can be test, how? Thank you so much!

  1. You don't need to test Ruby and Rails internals. Either you trust both of them do work as expected, or you'd better switch to some other language / framework.

  2. Whether you still want to test it, mock everything unrelated. Here is an example of doing this with rspec and flexmock .

describe '#update' do
  let(:person) { build(:people) }
  before do
    flexmock(People).should_receive(:find).once.returns person
    flexmock(person).should_receive(:update).once.returns false
  end

  it 'redirects to `edit` page' do
    ...
  end
end

Typically the update failure would be due to object to be saved not being valid, according to its validation criteria. You would normally test the validation criteria in the model specs, but when testing the controller, or in integration tests, you might want to ensure that the #edit render occurs when the user tries to save an invalid model.

If the model does not have any validation criteria, you can probably skip the else render:edit altogether. It's part of the Rails scaffold that may not apply in all cases.

You can test your update fail scenario by trying to save an invalid model. You would typically confirm that the user was correctly informed of the validity problem (flash message).

There's no right or wrong as to whether or not to test. Personally, I would test it, b/c I like TDD, and I prefer to over-test rather than under-test. Many would not.

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