0

I have a controller, and in my tests I want to do this:

%i(index show new create edit update destroy publish suspend).each do |action|
  # code
end

But it's verbose, and I need to do it in a number of tests. I know I can do the following:

ProjectsController.instance_methods.take(8).each do |action|
  # code
end

But it's brittle, especially if we remove the :suspend action. Is there a rails way of getting all the methods defined in a controller file, and no more.

1 Answer 1

2

You can do

ProjectsController.action_methods 

in your test. Any public method will be returned. Keep in mind do define any non action methods as private

If you want to do this for multiple controllers, you can have a look at shared example.

eg.

shared_examples "test actions" do
  controller_class.action_methods.each do |action|
    <your tests>
  end
end

and in your test file, simple say

it_behaves_like "test actions"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, for the answer, and the tip on shared_examples :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.