How I should test a Rails controller action which includes a method from lib/ directory?
My controller action:
def single
final_static_matrix = Single.final_static_matrix(a开发者_如何学运维verage_static_matrix, params[:priorities])
...
end
In my lib/single.rb:
module Single
def self.final_static_matrix(average_static_matrix = {}, priorities = {})
final_static_matrix = Hash.new
for i in 0..average_static_matrix.length-1
final_static_matrix[i.to_s] = average_static_matrix*priorities[i.to_s]
end
final_static_matrix
end
end
In my controller_spec.rb:
it "should be successful" do
get :single, :id => 1
priorities = {"0" => "1"}
matrix = {"0" => "3"}
Single.final_static_matrix(matrix, priorities)
response.should be_success
end
- How I should call the function from lib/ directory?
- How be better if i will write tests in controller file or create something like single_spec.rb?
What I would do: inside the controller-spec, I would test that the method gets called:
describe "GET :single" do
it "succeeds" do
Single.should_receive(:final_static_matrix).and_return('something')
get :single, :id => 1
end
end
and inside spec/lib/single_spec.rb
you test that the final_static_matrix
acts as expected.
You can check the documentation of rspec2 here.
If you've included it in your application, it should be available to you in your tests.
For controller tests, test the controller. You can do unit tests for the Library itself if you need seperately.
精彩评论