【问题标题】:How to include/set visible helper methods for rspec?如何为 rspec 包含/设置可见的辅助方法?
【发布时间】:2012-08-08 01:52:15
【问题描述】:

我在控制器 PlanetsController 中使用名为“generate_coordinate”(位于 app/helpers/planets_helper.rb 中)的方法。

运行测试时,rspec 似乎无法访问它,因此导致我的测试套件失败,因为地球没有任何坐标。

我尝试在 utilities.rb 文件的开头包含我的帮助程序,但没有成功

include ApplicationHelper
include PlanetsHelper

我也尝试将我的方法写入实用程序.rb 文件中,但没有更多成功。

我读了这篇文章“Where/how to include helper methods for capybara integration tests”,但对我没有帮助。

我也读过“存根”函数,但因为我不明白它可以用来做什么,所以对我没有多大帮助......

有什么想法吗?


这是我的测试代码 (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

当点击“Validate”时,会跳转到PlanetsController,它会调用“generate_coordinate”方法

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

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

这里是 generate_coordinate 方法,它似乎从未被 rspec 调用过(而当我使用浏览器浏览时)

module PlanetsHelper

    def generate_coordinates
        coordinates = "0.0.0.0"
    end

结束

【问题讨论】:

    标签: ruby-on-rails methods rspec visibility helper


    【解决方案1】:

    如果您的控制器和助手都使用您的generate_coordinate 方法,请考虑移入您的控制器(作为私有方法)并添加此单行代码以允许视图和助手访问它:

    # planets_controller.rb
    helper_method :generate_coordinate
    

    helper_method 将控制器方法公开给控制器范围内的视图和助手(在本例中为 planets#index、planets#show 等)。

    如果您想反其道而行之,您有两种选择:

    • 在控制器顶部插入include PlanetsHelper(在class PlanetsController下)
    • 当你想调用辅助方法时,这样调用它:view_context.generate_coordinate(...)

    试一试,看看哪一个最适合您的需求。

    【讨论】:

    • 感谢祖宾的回答。我还不清楚哪一部分代码可以被其他部分代码看到。例如: MycontrollerHelper 中的每个方法都应该在 MycontrollerController 中自动可见,对吧?这种方法也应该从“Mycontroller 的视图”中可见吗?因此,将方法包含在 Helper 文件中而不是直接包含在 Controller 文件中的意义何在?
    • 感谢您的编辑 Zubin,非常感谢您花时间向我解释一下这台机器。我会尝试你的两种解决方案。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    相关资源
    最近更新 更多