解释什么是respond_to? :应该在黄瓜?

时间:2013-04-04 23:57:19

标签: ruby-on-rails cucumber

我第一次在铁轨和黄瓜上使用红宝石。我正在尝试定义步骤定义,并希望有人可以解释我在步骤定义中找到的以下代码:

Then /^(?:|I )should see movies: "([^\"]*)"/ do |movie_list| #handles a text containing a text list of movies to check for
    if page.respond_to? :should
        page.should have_content(movie) #checks if movie appears on page
    else
    assert page.has_content?(text)
    end
end

我的情景是:

Scenario: all ratings selected
Given I am on the RottenPotatoes home page
Then I should see all movies

和 我正在尝试测试是否正在显示数据库中的所有项目。我应该在数据库的行上使用.shouldassert。我得到的提示是assert rows.should == value,但无法让它工作,因为我甚至不理解它!

因此,在进一步了解之后,我制作了以下方法来处理上述场景:

Then /^I should see all movies$/ do
  count = Movie.count
  assert rows.should == count unless !(rows.respond_to? :should)
end

但是黄瓜仍然没有失败。建议?

2 个答案:

答案 0 :(得分:4)

以下是逐行解释:

Then /^(?:|I )should see movies: "([^\"]*)"/ do |movie_list| #handles a text containing a text list of movies to check for
  # Does page respond to the should method? If it does, RSpec is loaded, and
  # we can use the methods from it (especially the should method, but
  # sometimes others)
  if page.respond_to? :should
    # Does the page contain the string that the movie variable refers to?
    # I'm not sure where this variable is being defined - perhaps you mean
    # movie_list?
    page.should have_content(movie) #checks if movie appears on page
  else
    # RSpec is not installed, so let's use TestUnit syntax instead, checking
    # the same thing - but it's checking against the variable 'text' - movie_list
    # again? Or something else?
    assert page.has_content?(text)
  end
end

考虑到所有这些 - 当您编写自己的步骤时,只需使用RSpec方法(如果您使用RSpec) TestUnit方法。您在步骤定义中无处不在if page.respond_to? :should

答案 1 :(得分:0)

好的,在您的步骤中,您的Given应告诉capybara访问正确的页面

Given ....
  visit '/url for movies'

这将访问网址并将页面加载到页面变量

Then /^(?:|I )should see movies: "([^\"]*)"/ do |movie_list| #handles a text containing a text list of movies to check for
    page.should have_content 'something that you are looking for'
end

如果您正在处理空白数据库,即没有电影,则需要在Given块中定义一部电影。

这里有一个非常好的介绍http://ruby.railstutorial.org/chapters/sign-in-sign-out#sec-cucumber