新手问题 使用 RSpec,helper 方法怎么定义呢?

0x9397 · 2015年09月18日 · 最后由 yue 回复于 2015年09月18日 · 1884 次阅读

各位好,请问一下,我使用 RSpec 替代 Rails 本身的 mini test,然后在 feature 和 controller 之类的 spec 里面想用到 helper 方法。看到教程里面是自己建立一个 support 之类的文件夹,在里面的 rb 文件中把 helper 方法写在 module 里面,再用 RSpec 的 config.include 来引入 helper 方法,但是不知道为什么,我这样写了却没有用。依然提示 undefined method。

# spec/support/authentication_helpers.rb
# sign_in_as!方法在 spec/features/***_sepc.rb中使用

module AuthenticationHelpers
  def sign_in_as!(user)
    visit '/sign_in'
    fill_in "Name", :with => user.name
    fill_in "Password", :with => "password"
    click_button "Sign in"
    page.should have_content("Signed in successfully.")
  end
end

Rspec.configure do |config|
  config.include AuthenticationHelpers, type: :features 
end

然后会提示

NoMethodError:
       undefined method `sign_in_as!' for #<RSpec::ExampleGroups::CreatingProjects:0x007f87b2303ef0>

不过直接在 spec_helper.rb 里面去写就没问题

# spec/spec_helper.rb

def sign_in_as!(user)
  visit '/sign_in'
  fill_in "Name", :with => user.name
  fill_in "Password", :with => "password"
  click_button "Sign in"
  page.should have_content("Signed in successfully.")
end

请问一下是什么问题呢?

可能的错误:

  • 没有 require。添加如下代码: ruby # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
  • 用错名字。检查文件文字,helper 名字
需要 登录 后方可回复, 如果你还没有账号请 注册新账号