2012-04-06 68 views
0

我正在使用Ruby on Rails 3.2.2和rspec-rails-2.8.1。我想在整個示例組中使用一個實例變量(在before鉤子中初始化),即使它在示例之外。也就是說,我願提出以下:如何在整個示例組中使用實例變量,即使它在示例之外?

describe "..." do 
    before(:each) do 
    @user = User.create(...) 
    end 

    # Here I would like to use the instance variable but I get the error: 
    # "undefined method `firstname' for nil:NilClass (NoMethodError)" 
    @user.firstname 

    it "..." do 
    # Here it works. 
    @user.firstname 
    ... 
    end 
end 

這可能嗎?如果是這樣,怎麼樣?


:我想這樣做,因爲我想輸出的更多信息有關將要運行的測試,這種方式:

# file_name.html.erb 
... 

# General idea 
expected_value = ... 

it "... #{expected_value}" do 
    ... 
end 

# Usage that i am trying to implement 
expected_page_title = 
    I18n.translate(
    'page_title_html' 
    :user => @user.firstname # Here is the instance variable that is called and that is causing me problems 
) 

it "displays the #{expected_page_title} page title" do 
    view.content_for(:page_title).should have_content(expected_page_title) 
end 
+1

爲什麼你甚至試圖做到這一點呢?你能否詳細說明你在做什麼? – davidcelis 2012-04-06 20:14:30

+0

@davidcelis - 我更新了問題。 – Backo 2012-04-07 00:41:21

+0

@Backo爲什麼你需要把期望值放在規格描述中? – 2012-04-07 01:04:21

回答

1

你不應該需要訪問RSpec設置,拆卸或測試塊之外的實例變量。如果您需要修改測試主題,您可能需要創建一個明確的主題,然後再使用之前進行訪問:

describe "..." do 
    subject { User.create(... } 

    before(:each) do 
    subject.firstname #whatever you plan on doing 
    end 

    it "..." do 
    # Here it works. 
    subject.firstname 
    ... 
    end 
end 
+0

我更新了問題。 – Backo 2012-04-07 00:40:45