【问题标题】:Rails RSpec testing a simple link redirect_to pathRails RSpec 测试一个简单的链接 redirect_to 路径
【发布时间】:2015-02-22 17:50:08
【问题描述】:

我在 Rails 应用程序中编写 RSpec 测试以确保来自我的应用程序主页的简单链接重定向到 about 页面时遇到困难。我的功能测试文件中有以下内容:

scenario "Have links redirect to the correct paths" do

  visit '/'

  click_link('about')
  expect(response).to redirect_to('about_index_path')

end

该链接的 id: 'about' 并且可以从浏览器进行测试,但我希望通过测试驱动开发做得更好。有什么建议么?我已经尝试了预期结果的多种变体,但我不断得到类似

NameError:
   undefined local variable or method `response'

NoMethodError:
   undefined method `assert_redirect_to'

当我把它放在控制器规范中时,我会得到类似

NoMethodError:
   undefined method `click_link'

如有必要,我可以提供更多信息,但我认为这应该是一个非常简单的解决方案(例如测试链接是否重定向到'http://www.google.com'),我只是没有找到。任何其他建议的方法表示赞赏。谢谢!

【问题讨论】:

    标签: ruby-on-rails rspec tdd capybara response.redirect


    【解决方案1】:

    response 在功能规范中不可用。如果您想在单击链接后断言用户在特定页面上,请尝试:

    expect(current_path).to eq about_index_path
    

    功能规范用于通过外部接口(例如浏览器)测试某些功能。在功能规范中,您通常会针对 page 对象进行断言。

    click_link 是一种 Capybara 方法,用于在功能规范而非控制器规范中模拟浏览器交互。控制器规范用于模拟单个 http 请求,该请求可以针对 response 对象进行断言。控制器规范非常适合测试重定向,尤其是到外部站点:

    describe "#index" do
      it "redirects to the google homepage"
        get :index
    
        expect(response).to redirect_to("http://www.google.com")
      end
    end
    

    如果您想在测试方面做得更好,我建议您学习不同类型的测试、何时使用它们以及如何编写它们。有很多很棒的资源可以帮助你。这是一篇很棒的文章,它解释了测试 Rails 应用程序的好方法:

    https://robots.thoughtbot.com/how-we-test-rails-applications

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多