我可以在RSpec请求中访问Application Helper方法吗?

roh*_*hra 18 rspec ruby-on-rails railstutorial.org

鉴于我full_title在ApplicationHelper模块中有一个方法,如何在RSpec请求规范中访问它?

我现在有以下代码:

app/helpers/application_helper.rb

    module ApplicationHelper

    # Returns the full title on a per-page basis.
    def full_title(page_title)
      base_title = "My Site title"
      logger.debug "page_title: #{page_title}"
      if page_title.empty?
         base_title
      else
        "#{page_title} - #{base_title}"
      end
    end
Run Code Online (Sandbox Code Playgroud)

spec/requests/user_pages_spec.rb

   require 'spec_helper'

   describe "User Pages" do
      subject { page }

      describe "signup page" do 
          before { visit signup_path }

          it { should have_selector('h2', text: 'Sign up') } 
          it { should have_selector('title', text: full_title('Sign Up')) } 

      end
    end
Run Code Online (Sandbox Code Playgroud)

在运行此规范时,我收到以下错误消息:

NoMethodError: undefined method full_title' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0x00000003d43138>

根据Michael Hartl的Rails教程中的测试,我应该能够在我的用户规范中访问应用程序帮助器方法.我在这里犯了什么错误?

iNu*_*lty 36

另一种选择是将其直接包含在spec_helper中

RSpec.configure do |config|
  ...
  config.include ApplicationHelper
end
Run Code Online (Sandbox Code Playgroud)


mni*_*chi 8

我正在使用每个gem的当前最新版本进行Ruby on Rails Tutorial(Rails 4.0版本).我遇到了类似的问题,想知道如何将ApplicationHelper包含在规范中.我使用以下代码:

投机/ rails_helper.rb

RSpec.configure do |config|
  ...
  config.include ApplicationHelper
end
Run Code Online (Sandbox Code Playgroud)

规格/请求/ user_pages_spec.rb

require 'rails_helper'

describe "User pages", type: :feature do
  subject { page }

  describe "signup page" do 
    before { visit signup_path }

    it { is_expected.to have_selector('h2', text: 'Sign up') } 
    it { is_expected.to have_selector('title', text: full_title('Sign Up')) } 
  end
end
Run Code Online (Sandbox Code Playgroud)

的Gemfile

...
# ruby 2.2.1
gem 'rails', '4.2.1'
...
group :development, :test do
  gem 'rspec-rails', '~> 3.2.1' 
  ...
end

group :test do
  gem 'capybara', '~> 2.4.4'
  ...
Run Code Online (Sandbox Code Playgroud)


ver*_*as1 1

spec/support/utilities.rb按照本书清单 5.26创建助手。

  • 据推测,它位于 application_helper.rb 中,因为您想在应用程序中使用它。将其移至 spec/ 可以防止这种情况发生,并且将其复制过来也不是很干燥。Nultyi 的方法是更好的方法。 (5认同)