Mocha Stubs가있는 예외 - rspec 테스트가 전달되지 않습니다
-
09-09-2020 - |
문제
이봐, 나는 Mocha와 Rspec을 사용하여 메소드가 항상 일부 예외를 제기하는 시나리오를 테스트하려고 노력하고 있습니다.
여기에 테스트하려고하는 컨트롤러 코드가 있습니다.
def add_parent
begin
parent = Entity.find_by_id(params[:parent_id])
if !parent.nil?
@entity.add_parent!(parent)
flash[:success] = "Entity successfully updated."
else
raise "Parent does not exist."
end
rescue
flash[:error] = "Something bad happened. #{$!}"
end
redirect_to @entity
end
.
여기에 테스트 코드가 있습니다 :
it "should flash error if exception is thrown when adding parent" do
Entity.any_instance.stubs(:add_parent!).raises(Exception)
lambda do
post :add_parent, :id => @entity[:id],
:parent_id => @parent_entity[:id]
end.should_not change(@entity.parents, :count)
flash[:error].should =~ /something bad happened/i
end
.
여기에 스텁되는 방법이 있습니다.
def add_parent!(parent)
Entity.transaction do
lock!('lock in share mode')
self.parents << parent
end
end
.
다음 RSPEC 오류가 발생하고 있으므로 꽤 정보가 없으므로 해결 방법을 모르겠습니다.
Failures:
1) EntitiesController POST 'add_parent' for signed-in users allow access with edit permission should flash error if exception is thrown when adding parent
Failure/Error: post :add_parent, :id => @entity[:id],
Exception
# ./app/controllers/entities_controller.rb:81:in `add_parent'
# ./spec/controllers/entities_controller_spec.rb:1010
. 해결책
Wooah, 무엇보다도 예상되는 예외 수업을 제공하지 않고 큰 덩어리로 구출하는 것은 매우 나쁜 습관입니다.모든 것을 구하면 좋지 않습니다.Best Rescueing을 최상으로 제거하고, AdereRacodicetagode를 통해 find
를 사용하므로 레일은 404 오류를 잡을 수 있고 괴롭히지 않아요.반면이 오류가 많이 일어날 것으로 예상되어 있습니까?일부 db-stock가 진행되는 것처럼 보입니다. 실패 할 것으로 기대하지 않을 것입니다.
둘째, find_by_id
에 대해 설명서와 같이 테스트해야합니다.
http : // relishapp..com / rspec / rspec-expectations / v / 2-6 / dir / 빌트 인 -meders / raiser-error-matcher
다른 팁
rescue
인하없이 표준식을 구하면됩니다.모든 예외를 저장하려면 모든 예외가 클래스 예외로부터 내려 져 있으므로 rescue Exception
를 입력해야합니다.
제휴하지 않습니다 StackOverflow