2014-11-10 2 views
1

브라우저에서 테스트하여 올바르게 작동합니다. 테스트 오류는 "예상 결과가 0에서 1로 변경되었지만 변경되지 않았습니다"라고 표시됩니다. 이것은 공장 문제입니까 rspec 문제입니까? 왜 변하지 않는거야?Rspec에서 컨트롤러를 사용하여 테스트 하시겠습니까?

오류 :

Failures: 

    1) ShortLinksController Short links controller Clicking a short link increments the click counter by 1 
    Failure/Error: expect{ get :url_dispatch, { id: short_link.short_link } }.to change{short_link.click_counter}.from(0).to(1) 
     expected result to have changed from 0 to 1, but did not change 
    # ./spec/controllers/short_links_controller_spec.rb:34:in `block (4 levels) in <top (required)>' 

RSpec에 :

it "increments the click counter by 1" do 
    short_link = create(:short_link) 
    expect{ get :url_dispatch, { id: short_link.short_link } }.to change{short_link.click_counter}.from(0).to(1) 
    end 

컨트롤러 :

def url_dispatch 
    id = params[:id] 
    record = ShortLink.where(["short_link = ?", id]).first 

    if record.update(click_counter: record.click_counter + 1) 
     redirect_to record.redirect_to 
    else 
     render '/not_found' 
    end 
    end 

공장 :

FactoryGirl.define do 
    factory :short_link do 
    redirect_to "http://google.com" 
    title "This is the google page" 
    short_link "xGh7u" 
    click_counter 0 
    owner Owner.create!(first_name: "Bob", last_name: "Diller", email: "[email protected]") 
    end 
end 
+0

팩토리 대신 모델을 호출하면 동일한 코드가 제대로 작동한다는 사실을 기반으로 한 'FactoryGirl'문제라고 생각합니다. 나는 컨트롤러 테스트에서이 문제를 해결하기 위해'reload'를 사용하고 있습니다.하지만 누군가 대답을하면 궁금합니다. – Anthony

+0

안녕하세요 @Anthony thats interesting. 나는 그것도 FG 문제라고 생각한다. 대답으로 작품을 게시 할 수 있습니까? 감사. – fyz

답변

1

Fab의 요청에 따라 다음과 같이 현재이 문제를 해결하는 방법을 알려드립니다. 여기

context 'save invocations' do 
    before(:each) do 
    @org = create(:organization) 
    user = create(:user, organization: @org, is_admin: true) 
    sign_in user 
    end 
    it 'valid scenario' do 
    user2 = create(:user, organization: @org, is_admin: false) 
    put :update, id: user2, user: { is_admin: true } 

    user2.reload 
    expect(response).to have_http_status(204) 
    expect(user2.is_admin).to eq true 
    end 
end 

나는 사용자 2 공장에서 업데이트 된 특성을 얻기 위해 user2.reload를 호출하고 있습니다.

나는 expect{} 구문은 공장 작동하지 않는 이유를 모르지만이 같은 코드 리팩토링 수 :이, 난 그냥 '나오지 않았어 가장 좋은 방법은 내가 말하는 게 아니에요

다시
it "increments the click counter by 1" do 
    short_link = create(:short_link) 
    count = short_link.click_counter 
    get :url_dispatch, { id: short_link.short_link } 
    short_link.reload 

    expect(short_link.click_counter).to eq count + 1 
    end 

입니다 RSpec 3에 관한 FactoryGirl 문서에서 속성을 업데이트하는 컨트롤러에서 구문을 기대합니다.

+1

Anthony +1에 감사드립니다. – fyz

+1

나는 이것을 연구하려고 노력했다. 내가 발견 할 수있는 것으로부터, 이것이 적절한 구현이라고 믿기 시작했다. 누군가가 따라 와서 더 좋은 방법을 제공하지 않는 한. 나는 당신의 대답을 받아 들일 것입니다. – fyz

+0

좋은 소식 - 'FactoryGirl'핵심 팀원 중 누구라도 '우수 사례'를 갖고 있다면 궁금합니다. – Anthony

관련 문제