0

我试图让我的代码更小一些,构建一个看起来像 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')

这些方法是如何构建的?

4

3 回答 3

2

简单的:

类对象
  def should_receive(味精)
    self.send(msg.to_sym)
    自己
  结尾
  def and_transition_to(状态)
    @state == 状态
  结尾
  定义添加
    @state = '添加'
  结尾
结尾  

现在你可以运行:

obj = Obj.new
obj.should_receive(:add).and_transition_to('adding')
=> 真
于 2011-06-02T18:22:44.167 回答
0

它不是 ruby​​-on-rails,但本文给出了Fluent Interface的示例。

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;
    }
    :
于 2011-06-02T17:52:47.663 回答
0

链接的重要部分是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
于 2011-06-02T21:05:39.380 回答