11

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

鉴于我有:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

我有以下黄瓜功能:

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 步骤吗?我是否以错误的方式思考问题?

4

2 回答 2

18

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

when /the children list page for "(.+)"/
    p = Parent.find_by_name($1)
    parent_children_path(p)
于 2010-01-15T23:01:52.480 回答
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)
于 2010-07-08T00:16:37.870 回答