2
votes

I use a method named "generate_coordinate" (located in the app/helpers/planets_helper.rb) in my controller PlanetsController.

When running tests, it seems that rspec isn't able to access it, and so cause my test suite to fail because the planet doesn't have any coordinates.

I tried to include my helper at the beginning of the utilities.rb file, but it didn't work

include ApplicationHelper
include PlanetsHelper

I also tried to write my method inside the utilities.rb file, without more success.

I read this post "Where/how to include helper methods for capybara integration tests", but it didn't help me.

I also read about "stub" functions, but because I can't understand what it could be used for, it didn't help me much...

Any idea ?


Here is my test code (spec/requests/planet_pages_spec.rb)

describe "Create planet" do
    before do
        visit new_planet_path
        fill_in "Name", with: "MyPlanet"
        click_button "Validate"
    end

    it {should have_selector('h1', text: "Planet")}
end

When click on "Validate", it leads to the PlanetsController, which calls the "generate_coordinate" method

def create
    @planet = Planet.new(name: params[:planet][:name],
        coordinates: generate_coordinates, [...])

        if @planet.save
            redirect_to action: 'index'
        else
            render 'new'
        end

And here is the generate_coordinate method, which seems never been called by rspec (whereas it is when I navigate through with my browser)

module PlanetsHelper

    def generate_coordinates
        coordinates = "0.0.0.0"
    end

end

1

1 Answers

0
votes

If your generate_coordinate method is used by both your controller and helper, consider moving into your controller (as a private method) and adding this one-liner to allow views and helpers to access it:

# planets_controller.rb
helper_method :generate_coordinate

helper_method exposes controller methods to views and helpers within the scope of the controller (in this case, planets#index, planets#show, etc).

If you'd rather do it the other way round you have two options:

  • insert include PlanetsHelper at the top of the controller (under class PlanetsController)
  • when you want to call the helper method, call it like this: view_context.generate_coordinate(...)

Try them out and see which one suits your needs best.