简体   繁体   English

如何在控制器中测试特定方法

[英]How to test a specific method in a controller

I have a spec in my controller called clone in which I take a user and clone the duplicate the user. 我的控制器中有一个名为clone的规范,其中包含一个用户并克隆该用户的副本。

What I need to do is within my controller (my model is player and so controller is player_controller.rb , I need to test a specific method listed below. 我需要做的是在控制器内(我的模型是player ,所以控制器是player_controller.rb ,我需要测试下面列出的特定方法。

def clone
  new_player = @player.dup
  new_player.id = nil
  new_player.serial = nil
  new_player.name = "Copy of #{@player[:name]}"
end

describe '#clone' do
  it 'creates a clone of an existing player' do
    new_player = player.dup
  end
end

Sure what I have done in my spec is mirror the first line in the method within the controller, and so it creates a new player for me, but it doesn't update the additional features of the spec such as the name. 确保我在规范中所做的工作是在控制器内方法的第一行进行镜像,因此它为我创建了一个新播放器,但不会更新规范的其他功能,例如名称。 And that is what I am having trouble. 这就是我遇到的麻烦。 How can I specifically call out a method within my controller? 如何在控制器中专门调出方法?

I've tried 我试过了

new_player = player.controller.send(:clone)

as well as 以及

new_player = player.(:clone)

The first error does not recognize clone and the second error states that I am getting an undefined method "call" for player. 第一个错误无法识别clone ,第二个错误指​​出我正在获取播放器的未定义方法“调用”。 (I don't quite understand that error) (我不太明白该错误)

Would anybody know how to pull that guy out so I can test it? 有人知道如何把那个家伙拉出来以便我测试吗?

Much appreciated. 非常感激。

In the end your controller is nothing but a Ruby class. 最后,您的控制器不过是一个Ruby类。 Create an instance of it and call the method clone for the object you just created. 创建它的一个实例,并为刚创建的对象调用方法clone。

PlayerController.new.clone

or 要么

PlayerController.new.send(:clone)

The issue I see here is, from where is the @player getting initialised? 我在这里看到的问题是,@ player是从哪里初始化的? There will be no constructor for this class(as it is a controller). 此类将没有构造函数(因为它是一个控制器)。 If there is some other method say 'my_test_method', that initialises it. 如果还有其他方法说“ my_test_method”,则将其初始化。 Then call that method first on the PlayerController object and then call the clone method on the same object. 然后,首先在PlayerController对象上调用该方法,然后在同一对象上调用clone方法。

my_object = PlayerController.new
my_object.my_test_method
my_object.clone

If the clone method is getting called from an action where @player is set. 如果从设置@player的操作中调用了clone方法。 Then include the specs for this method as part of the specs you are writing for that action. 然后将此方法的规范作为您为该操作编写的规范的一部分。

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

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