Huy
Huy

Reputation: 11206

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.

I have two questions.

  1. Should this method be in a helper and not in the controller itself (per Rails convention)?

  2. How do I submit a get request and pass params in my test?

Upvotes: 1

Views: 1382

Answers (1)

zetetic
zetetic

Reputation: 47548

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).

Upvotes: 1

Related Questions