2012-03-13 159 views
5

我一直當我使用水豚方法的外塊之前得到這個奇怪的錯誤:未定義的局部變量或方法豚rspec的

$ rspec . -e "PasswordResets" 
/spec/requests/password_resets_spec.rb:9:in `block (2 levels) in <top (required)>': undefined local variable or method `root_path' for #<Class:0x00000003bfa100> (NameError) 

root_path確實存在。我有多個其他測試工作。但是看起來我只能在方塊在before塊內時才能使用水豚。這工作:

require 'spec_helper' 
describe "PasswordResets" do 
    subject { page } 
    describe "it emails user when requesting a password reset" do 
    before do 
     visit root_path 
    end 
    end 
end 

這會產生錯誤:

require 'spec_helper' 
describe "PasswordResets" do 
    subject { page } 
    describe "it emails user when requesting a password reset" do 
    visit root_path 
    end 
end 

這工作:

require 'spec_helper' 
describe "PasswordResets" do 
    it "emails user when requesting a password reset" do 
    visit root_path 
    end 
end 

我想要做的就是使用subject { page },但能夠使用水豚,而不必使用before do end塊。任何想法我做錯了什麼?

spec_helper.rb文件:

ENV["RAILS_ENV"] ||= 'test' 
require File.expand_path("../../config/environment", __FILE__) 
require 'rspec/rails' 
require 'rspec/autorun' 
require 'capybara/rspec' 

Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} 

RSpec.configure do |config| 
    config.fixture_path = "#{::Rails.root}/spec/fixtures" 
    config.use_transactional_fixtures = true 
    config.infer_base_class_for_anonymous_controllers = false 
end 

我on Rails的3.2與水豚1.1.2,2.8.1 Rspec的。

+0

你不需要使用'before(:all)'或'before(:each)'嗎?我並不認爲'以前做'本身是有效的。 – jefflunt 2012-03-13 18:41:51

回答

8

您不能直接在describe中放置測試代碼。範圍是不同的。把它放在beforeit塊中。

+0

看到我是Ruby和RoR的新手,你是否會友好地解釋爲什麼發生這種情況,以及範圍/描述塊的工作方式?我不是懶惰的,我只是沒有找到足夠的「傻瓜」來消化... – Mohamad 2012-03-13 23:56:49

+2

Mohamad,我推薦RSpec書作爲一個好地方開始。基本的基本原理是,「描述」塊中唯一的內容是「之前」,「上下文」和「它」塊 – 2012-03-23 01:30:25

相關問題