0

我有以下控制器测试用例:

def test_showplain
  Cleaner.expect(:parse).with(@somecontent)
  Cleaner.any_instance.stubs(:plainversion).returns(@returnvalue)

  post :showplain, {:content => @somecontent}

end

这很好用,除了我希望“stubs(:plainversion)”成为“expects(:plainversion)”。

这是控制器代码:

def showplain
   Cleaner.parse(params[:content]) do | cleaner |
      @output = cleaner.plainversion
   end
end

Cleaner 很简单:

class Cleaner

   ### other code and methods ###

   def self.parse(@content) 
     cleaner = Cleaner.new(@content)
     yield cleaner
     cleaner.close
   end

   def plainversion
      ### operate on @content and return ###
   end

end

同样,我不知道如何可靠地测试“解析”方法提供的“清洁器”。有什么建议么?

4

2 回答 2

0

This is a little tricky. The easiest a approach will be to break the problem into two pieces: the testing of the controller and the testing of the controller.

You have the testing of the controller set-- just remove your expectation around plainversion call.

Then, separately, you want to test the Cleaner.parse method.

cleaner = Cleaner.new('x');
cleaner.expects :close

Cleaner.expects(:new).returns(cleaner)

called_with = nil
Cleaner.parse('test') do |p|
  called_with = p
end
assert_equal p, cleaner

That is not very clear what's going on. Makes me think that there is a simpler version of this. Can cleaner just be a simple function that takes a string and returns another one? Skip all the yielding and variable scoping? That will be much easier to test.

于 2010-05-13T15:51:51.263 回答
0

您可能会发现Mocha::Expectation#yields的文档很有用。

我已经尝试在这个要点中展示你如何做你想做的事。请注意,我必须稍微调整代码以使其成为独立的可运行测试。

于 2010-12-02T11:36:31.533 回答