简体   繁体   English

RSpec - 如何在 controller 的更新方法中测试 if-else 块

[英]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. 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.我在 StackOverflow 上搜索过它,有一个关于它的链接,但它没有说明我是否应该或不应该测试它。 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.您无需测试 Ruby 和 Rails 内部。 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 .这是使用rspecflexmock执行此操作的示例。

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.根据其验证标准,更新失败通常是由于要保存的 object 无效。 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.您通常会在 model 规范中测试验证标准,但在测试 controller 或集成测试时,您可能希望确保在用户尝试保存无效的 Z20F35E630DAF459DBFA4C3F68D 时发生 #edit 渲染

If the model does not have any validation criteria, you can probably skip the else render:edit altogether.如果 model 没有任何验证标准,您可以完全跳过else render:edit It's part of the Rails scaffold that may not apply in all cases.它是 Rails 脚手架的一部分,可能并不适用于所有情况。

You can test your update fail scenario by trying to save an invalid model.您可以通过尝试保存无效的 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.就个人而言,我会测试它,因为我喜欢 TDD,而且我更喜欢过度测试而不是测试不足。 Many would not.许多人不会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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