简体   繁体   English

Rspec控制器测试-如何将参数传递给我正在测试的方法

[英]Rspec controller test - how to pass arguments to a method I'm testing

I want to test this method in my controller. 我想在控制器中测试此方法。

def fetch_match_displayed_count(params)
  match_count = 0
  params.each do |param|
    match_count += 1 if param[1]["result"] && param[1]["result"] != "result"
  end
  match_count
end

This is the test I've written so far. 这是我到目前为止编写的测试。

describe "fetch_match_displayed_count" do
  it "should assign match_count with correct number of matches" do
    params = {"result_1"=>{"match_id"=>"975", "result"=>"not_match"}, "result_2"=>{"match_id"=>"976", "result"=>"match"}, "result_3"=>{"match_id"=>"977", "result"=>"not_sure"}, "result_4"=>{"match_id"=>"978", "result"=>"match"}, "result_5"=>{"match_id"=>"979", "result"=>"not_match"}, "workerId"=>"123", "hitId"=>"", "assignmentId"=>"", "controller"=>"mt_results", "action"=>"create"}
    controller.should_receive(:fetch_match_displayed_count).with(params)
    get :fetch_match_displayed_count, {params:params}
    assigns(:match_count).should == 5
  end
end

My problem seems to lie in this line get :fetch_match_displayed_count, {params:params} The method is expecting params, but is getting nil. 我的问题似乎在这行中get :fetch_match_displayed_count, {params:params}该方法正在使用params,但是得到nil。

I have two questions. 我有两个问题。

  1. Should this method be in a helper and not in the controller itself (per Rails convention)? 此方法是否应该在帮助程序中,而不应该在控制器本身中(按照Rails约定)?

  2. How do I submit a get request and pass params in my test? 如何在测试中提交获取请求并通过params

As a general rule, you should test the public interface of your class. 通常,您应该测试类的公共接口。 For a controller, this means you test actions, not helper methods. 对于控制器,这意味着您要测试操作,而不是辅助方法。

You should be able to make this work by setting up one or more separate test cases that call the appropriate action(s), then use a message expectation to test that the helper method is called with the right arguments -- or test that the helper method does what it is supposed to do (sets the right instance variables/redirects/etc). 您应该能够通过设置一个或多个单独的测试用例来调用适当的操作来完成这项工作,然后使用消息期望来测试是否使用正确的参数调用了helper方法,或者测试了helper方法执行应做的事情(设置正确的实例变量/重定向/等)。

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

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