example how to use 'stub' and 'mock' in sepc
程序员文章站
2022-06-07 14:25:15
...
Use sometime to learn stub and mock.
I think below is a good example:
code:
def create_from_content(content)
page_content = PageContent.new(content)
templet = page_content.templet
templet_id = page_content.templet_id
page_title = page_content.page_title
#OPTIMIZE
Page.update_all("title = '#{escape_single_quotes(page_title)}', templet_id='#{templet_id}'", "id=#{self.id}" )
self.page_parts.create_from_content(page_content.content_without_title, templet)
self.reload
return self
end
test:
describe "create_from_content" do
it "should create page's atrributes from content" do
page = Page.create
page_content = mock(PageContent, :templet_id => 1, :page_title => "page_title", :content_without_title => "content_without_title", :templet => "templet")
PageContent.stub!(:new).with("content").and_return(page_content)
page.stub!(:escape_single_quotes).with("page_title").and_return("page_title")
page.page_parts.stub!(:create_from_content).with("content_without_title", "templet").and_return(nil)
page.create_from_content("content").should == page
page.title.should == "page_title"
page.templet_id.should == 1
end
end
下一篇: 修改第三方组件样式