我试图让我的代码小一点,构建一个看起来像来自RSpec的should_receive的方法,这里的情况是我正在测试一个状态机,我有几个方法的代码如下:
context "State is unknown" do
before do
@obj = create_obj(:state => 'unknown')
end
context "Event add" do
it 'should transition to adding if not in DB' do
@obj.add
@obj.state.should == 'adding'
end
it 'should transition to linking if already in DB' do
create_obj_in_db
@obj.add
@obj.state.should == 'linking'
end
end
end
我想把这些代码行替换成类似的东西:
@obj.should_receive(:add).and_transition_to('adding')
@obj.should_receive(:modify).and_transition_to('modifying')
这些方法是如何构建的?
简单:
类Objdef should_receive(消息)self.send(消息.to_sym)自己终止def和_transition_to(状态)@state==状态终止def添加@state="正在添加"终止终止
现在你可以运行:
obj=对象新建obj.should_receive(:add).and_transition_to('adding')=>真
链接的重要部分是从对象返回self
,因此下一次调用仍然可以对对象进行操作。
class Foo
def one
puts "one"
self
end
def two
puts "two"
self
end
def three
puts "three"
self
end
end
a=Foo.new
a.one.two.three
它不是ruby on rails,但本文给出了一个Fluent接口的示例。
public class Pipeline
{
private Image image;
public Image CurrentImage
{
get { return image; }
set { image = value; }
}
public Pipeline(string inputFilename)
{
image = Bitmap.FromFile(inputFilename);
}
public Pipeline Rotate(float Degrees)
{
RotateFilter filter = new RotateFilter();
filter.RotateDegrees = Degrees;
image = filter.ExecuteFilter(image);
return this;
}
: