【问题标题】:Rspec controller test - how to pass arguments to a method I'm testingRspec 控制器测试 - 如何将参数传递给我正在测试的方法
【发布时间】:2013-02-01 10:41:39
【问题描述】:

我想在我的控制器中测试这个方法。

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

这是我目前写的测试。

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

我的问题似乎出在这一行get :fetch_match_displayed_count, {params:params} 该方法需要参数,但结果为零。

我有两个问题。

  1. 此方法是否应该在帮助程序中而不是在控制器本身中(根据 Rails 约定)?

  2. 如何提交获取请求并在测试中通过params

【问题讨论】:

  • 这是一个动作吗?我猜没有。
  • @zetetic 不,这是我在创建操作中调用的方法。
  • 我能够弄清楚这一点。我必须将该方法设为私有方法,然后在 create 操作上提交获取请求。然后,我可以期待以下内容:controller.should_receive(:fetch_match_displayed_count).with(params).and_return(5)
  • 呵呵..秒杀我。 :)

标签: ruby-on-rails ruby-on-rails-3 rspec capybara


【解决方案1】:

作为一般规则,您应该测试类的公共接口。对于控制器,这意味着您测试的是操作,而不是辅助方法。

您应该能够通过设置一个或多个单独的测试用例来调用适当的操作,然后使用消息期望来测试是否使用正确的参数调用了辅助方法 - 或测试帮助方法完成它应该做的事情(设置正确的实例变量/重定向/等)。

【讨论】:

  • 太好了,谢谢 zetetic。您在我的帖子中提出的问题帮助我解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-19
相关资源
最近更新 更多