2010-04-25 87 views
1

上下文較小的代碼示例再次問這個問題:如何創建早該宏

# this is a dummy shoulda macro that creates a context 
    def self.macro_context 
    context "macro" do 
     yield 
    end 
    end 

    # i am expecting this test to fail within the macro context 
    context "some context" do 
    macro_context do 
     should "test" do 
     fail 
     end 
    end 
    end 

那麼我希望是看到:

1) Error: 
    test: some context macro context should test. (TestClassName) 

但我只得到了這一點:

那麼我希望是看到:

1) Error: 
    test: some context should test. (TestClassName) 

任何想法我做錯了什麼?

回答

1

感謝舊金山的代碼,來解決這個問題,你不能只是產生新的上下文內的塊,你必須使用早該的merge_block方法。然後它應該看起來像這樣:

def self.macro_context(&block) 
    context "macro" do 
     merge_block(&block) 
    end 
    end 
2

我的代碼中有類似的東西。我做了這樣的成test/shoulda_macros/whatever_file.rb

def self.should_require_login(actions = [:index], &block) 
if (actions.is_a? Symbol) 
    actions = [actions] 
end 
context "without user" do 
    actions.each do |action| 
    should "redirect #{action.to_s} away" do 
     get action 
     assert_redirected_to login_path 
    end 
    end 
end 
if block_given? 
    context "active user logged in" do 
    setup do 
     @user = Factory.create(:user) 
     @user.register! 
     @user.activate! 
     login_as(@user) 
    end 

    merge_block(&block) 
    end 
end 
end 
+0

唯一的區別似乎是merge_block調用,我沒有看到過,它是做什麼的? – Honza 2010-04-26 09:32:56

+0

正如其名稱所示,它會將您傳遞的塊與您調用'merge_block'的塊合併。在你的情況下,它會將給定的塊合併到「context」活動用戶登錄的「do ... end」中 – Fran 2010-04-26 13:48:27