【问题标题】:Cucumber and webrat - How to handle dynamic URLs in the paths.rb?Cucumber 和 webrat - 如何处理 paths.rb 中的动态 URL?
【发布时间】:2011-01-05 16:01:42
【问题描述】:

我在我的 Ruby on Rails 项目中使用 Cucumber 进行 BDD 开发,我对 path.rb 如何处理 rails 应用程序中使用的路径感到有些困惑。

鉴于我有:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

而且我有以下 Cucumber 功能:

Scenario: A test feature
    Given I am on the parent page
     When I follow "Link to Children"
     Then I should be on the children list page

路径定义为:

def path_to(page_name)
  case page_name
  when /the children list page/
       '/parents/:id/children'
end

我遇到的问题是运行该功能时出现以下错误:

Spec::Expectations::ExpectationNotMetError: expected: "/parents/:id/children",
 got: "/parents/1726/children" (using ==)

我并不关心 :id 是什么。我应该怎么做?这甚至可以通过默认的 Web 步骤实现吗?我是否以错误的方式思考问题?

【问题讨论】:

    标签: ruby-on-rails cucumber webrat


    【解决方案1】:

    我这样做的方式,可能不是最好的方式如下:

    when /the children list page for "(.+)"/
        p = Parent.find_by_name($1)
        parent_children_path(p)
    

    【讨论】:

      【解决方案2】:

      在我们的应用程序中,每当用户单击“新建”按钮时,我们总是希望数据库中有一条新记录。因此,我们控制器的新操作会自动调用 create,然后重定向到编辑操作。

      我们在测试中遇到了类似的问题,当时我们不太关心 ID 是什么——只是它到达了应用的编辑页面。

      这是我想出的。

      (注意:步骤定义是用capybara写的,但应该和webrat差别不大)

      Then /^(?:|I )should now be editing the (.*)$/ do |model|
        id = find_by_id("#{model}_id").value
        Then "I should be on the edit #{model} page for \"#{id}\""
      end
      

      基本前提是,当您在 Rails 编辑页面上时,您正在编辑的模型会有一个表单。该表单始终包含一个隐藏字段,其中包含您正在编辑的特定记录的 ID。

      该步骤找到隐藏字段,从中提取 ID,然后查找 web_step 以解析该模型的路径。

      只需确保您的路径与您正在查找的模型相匹配。

      when /the edit person page for "([^\"]*)"/
        edit_person_path($1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-19
        • 2010-11-25
        • 1970-01-01
        • 2019-03-19
        • 1970-01-01
        • 2010-12-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多