2014-01-27 69 views
0

有没有办法来重构这个避免重复:我如何可以重构这些断言,以避免重复

post :create, user: attributes_for(:user) 

鉴于第一个断言需要将其包装在expect块,我不知道看到一种将它移动到before块的方法。很明显,我可以将最后两个断言封装在contextdescribe块中,并使用它自己的before块,但这不太合适。

context 'with valid attributes' do 

    it 'should create a new User and save it to the database' do 
     expect { 
     post :create, user: attributes_for(:user) 
     }.to change(User, :count).by(1) 
    end 

    it { 
     post :create, user: attributes_for(:user) 
     should redirect_to(user_path(assigns[:user])) 
    } 

    it { 
     post :create, user: attributes_for(:user) 
     should set_the_flash[:notice] 
    } 

    end 

回答

1

你可以把你的 “行动” 的方法,具体如下:

context 'with valid attributes' do 
    it 'should create a new User and save it to the database' do 
    expect { 
     do_action 
    }.to change(User, :count).by(1) 
    end 

    it { 
    do_action 
    should redirect_to(user_path(assigns[:user])) 
    } 

    it { 
    do_action 
    should set_the_flash[:notice] 
    } 

    def do_action 
    post :create, user: attributes_for(:user) 
    end 
end 
0

像这样的东西(不确保它的工作原理)

context 'with valid attributes' do 
    before { post :create, user: attributes_for(:user) } 

    it 'should create a new User and save it to the database' do 
     expect(User.count).to eq 1 
    end 

    it { should redirect_to(user_path(assigns[:user])) } 
    it { should set_the_flash[:notice] } 
    end