2011-06-02 1 views
0

Я пытался сделать свой код немного меньше, построив метод, который может выглядеть как must_receive от RSpec , дело в том, что я тестирую государственную машину и у меня есть несколько методов, с кодом, как это:Как построить цепные методы, такие как - should_receive (: something) .with (: params, values) .and_return (: something_else)

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') 

Как создаются эти методы?

ответ

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 
0

Это не рубиновые рельсы, а this article дает пример 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; 
    } 
    : 
2

Простой:

 
class Obj 
    def should_receive(msg) 
    self.send(msg.to_sym) 
    self 
    end 
    def and_transition_to(state) 
    @state == state 
    end 
    def add 
    @state = 'adding' 
    end 
end 

Теперь вы можете запустить:

 
obj = Obj.new 
obj.should_receive(:add).and_transition_to('adding') 
=> true 
Смежные вопросы