2015-12-05 44 views
0

我試圖測試一個非常(和非邏輯)的ruby類。Ruby Minitest使用不同測試的存根

class Post 
    attr_accessor :title 
    def initialize 
    @title = "Treehouse Blog" 
    end 
end 

class Blog 
    def create_and_get_title 
    post = Post.new 
    post.title 
    if post.title == nil 
     post2 = Post.new 
     post2.title 
    else 
     post.title 
    end 
    end 
end 

,這裏是我的測試:

require 'minitest/autorun' 
require_relative 'blog' 
require 'ostruct' 

class TestBlog < Minitest::Test 
    def setup 
    @blog = Blog.new 
    end 

    def test_title_is_treehouse_blog 
    assert_equal('Treehouse Blog', @blog.create_and_get_title) 
    end 

    def test_title_is_yyy 
    def Post.new; OpenStruct.new(title: nil) end 
    def Post.new; OpenStruct.new(title: 'yyy') end 
    assert_equal('yyy, @blog.create_and_get_title) 
    end 
end 

簡單,對不對?不過,我得到以下輸出從運行測試:

1) Failure: 
TestBlog#test_title_is_treehouse [test.rb:12]: 
Expected: "Treehouse Blog" 
    Actual: "yyy" 

我不明白在每次運行失敗,我只是把它隨意,看起來像被緩存在存根或東西。

任何想法?

非常感謝!

+1

在'assert_equal'調用中'test_title_is_yyy'方法中有語法錯誤。報價缺失。 – Tobias

回答

1

你已經實現了這個方法,你實際上並沒有將該方法存根存根,而是將其替換,並且每次首先運行test_title_is_yyy時都會發生同樣的故障。解決方法是使用Object#stub到只有一個街區的範圍之內更換存根方法:

def test_title_is_yyy 
    Post.stub(:new, OpenStruct.new(title: 'yyy')) do 
    assert_equal('yyy, @blog.create_and_get_title) 
    end 
end 

順便說一句,使用def作爲存根,更換完全是罰款,如果你磕碰實例方法。儘管如此,您仍然在使用類方法,並且由於該類不會在測試之間重新加載,因此您已經爲測試運行的其餘部分重新定義了new