使用Capybara和Cucumber时出现"Undefined method 'should'"错误

5

我正在尝试在我的Rails应用程序中同时使用Capybara和Cucumber。 所以,这就是我所做的:

  • 安装所需的gems并将它们添加到Gemfile
  • 运行rails generate capybara:install --cucumber
  • 为Cucumber创建了一个feature和其步骤定义

这是我的feature(是的,我正在创建博客应用程序):

Feature: Browse posts
    So that I can browse through the posts
    As a visitor
    I want to see all and/or particular posts

    Scenario: Viewing all the posts
        Given Posts exist
        When I navigate to the website home
        Then I should see all the posts

    Scenario: Viewing particular post
        Given Post #1 exists
        When I navigate to /posts/view/1
        Then I should see the post with id=1

这里是其步骤定义:

Given /^Posts exist$/ do
    assert (not Post.all.empty?), "No posts found at all"
end

Given /^Post #(\d+) exists$) do |id|
    assert Post.find_by_id(id).valid?, "Post ##{ id } was not found at all"
end

When /^I navigate to (.+)$/ do |url|
    if url =~ /^the website home$/ then
        visit '/'
    else
        visit url
    end
end

Then /^I should see all(.+)posts$/ do |delimiter|
    posts = Post.all

    posts.each do |post|
        page.should have_content post.title
    end
end

Then /^I should see the post with id([^\d]{1,})(\d+)$/ do |delimiter, id|
    post = Post.find_by_id id

    page.should have_content post.title
end

当运行rake cucumber时,我收到了这个消息:

Then I should see all the posts     # features/step_definitions/browsing_posts.rb:13
  undefined method `should' for #<Capybara::Session> (NoMethodError)
  ./features/step_definitions/browsing_posts.rb:17:in `block (2 levels) in <top (required)>'
  ./features/step_definitions/browsing_posts.rb:16:in `each'
  ./features/step_definitions/browsing_posts.rb:16:in `/^I should see all(.+)posts$/'
  features/browsing_posts.feature:9:in `Then I should see all the posts'

我做错了什么?另外,我的功能中有错误吗?

1
这并不能解决你的问题,但可以提高你故事的质量:Given nothing 是不正确的。更可能是你想要 Given Posts exist - Daniel Hilgarth
你是使用默认的test::unit还是使用rspec?你的一些语法更像是rspec的风格。 - prusswan
@prusswan,实际上,我不确定 =)我使用rake cucumber运行测试,我没有看到任何由我提供的__rspec__或__test::unit__代码。我想cucumber使用它自己的类。 - shybovycha
在这种情况下,您正在使用默认的test-unit,并且应该使用附带的期望语法。 - prusswan
@prusswan 什么是 expectation syntax ?我没有理解你的想法 - 你是否在谈论 assert 的用法? - shybovycha
3个回答

17

page.should have_content post.title替换为assert page.has_content?(post.title)。如果这样可以,请类似地应用于其他have_content语句。

编辑:那些涉及should语句基于rspec expectations,只有在您已经使用rspec或某个其他测试框架响应should时才应该使用。从test::unit的角度来看,这可能只是另一种assert


你在哪里找到适用于Minitest的“asserts”列表? - undefined

4

你能试一下吗?

page.has_content?('foo')

代替

页面应该有内容post.title

如果它起作用了,那么你可以与assert一起使用。


2

在遇到相同问题后,我尝试了

expect(page).to have_content('foo')

这对我来说很有效


这意味着您正在使用更新版本的RSpec。 - rep

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接