有没有办法重构这个以避免重复:
post :create, user: attributes_for(:user)
鉴于第一个断言需要将其包装在expect
块中,我没有看到将其移动到before
块的方法。显然,我可以使用自己的context
块在describe
或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
答案 0 :(得分: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
答案 1 :(得分: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