控制器RSpec:使用自定义ID测试PATCH更新

时间:2014-01-23 00:50:30

标签: ruby-on-rails rspec

我遇到挑战为PATCH更新编写RSpec控制器测试,因为路由和编辑使用我的模型生成的安全edit_id,而不是标准1,2,3,4,5 Rails自动生成的(序列id)。基本上,我不知道如何使用此edit_id来查找要编辑的请求。

我目前的测试:

describe "PATCH edit/update" do

    before :each do
        @testrequest = FactoryGirl.build(:request, name: "James Dong")
    end

    it "located the requested @testrequest" do
        patch :update, id: @testrequest.edit_id, request: FactoryGirl.attributes_for(:request)
        assigns(:request).should eq(@testrequest)
    end

    describe "using valid data" do

        it "updates the request" do
            patch :update, @testrequest.name = "Larry Johnson" 
            @testrequest.reload
            @testrequest.name.should eq("Larry Johnson")
        end
    end

FactoryGirl 帮助器(我已经尝试过两次显式添加edit_id而不是[即依赖模型来创建edit_id本身],但两者都没有区别)代码:

FactoryGirl.define do
    factory :request do |f|
        f.name { Faker::Name.name }
        f.email { Faker::Internet.email }
        f.item { "random item" }
        f.detail { "random text" }
        f.edit_id { "random" }
    end
end

控制器

def update
    @request = Request.find_by_edit_id(params[:edit_id])
    if @request.update_attributes(request_params) 
    flash[:success] = "Your request has been updated! We'll respond within one business day."
    redirect_to edit_request_path(@request.edit_id)
    else
    render 'edit'
    end
end

路由

get 'edit/:edit_id', to: 'requests#edit', as: 'edit_request'
patch 'requests/:edit_id', to: 'requests#update', as: 'request'

1 个答案:

答案 0 :(得分:2)

好的,有人帮我搞清楚了,我觉得很傻。 " id"你传递给补丁方法的可以是任何id,所以我不应该尝试设置id:edit_it,而应该首先使用edit_it。即,有效的代码:

before :each do
    @testrequest = FactoryGirl.build(:request, name: "James Dong")
end

it "located the requested @testrequest" do
    patch :update, edit_id: @testrequest.edit_id, request: FactoryGirl.attributes_for(:request)
    assigns(:request).should eq(@testrequest)
end

describe "using valid data" do

    it "updates the request" do
        patch :update, edit_id: @testrequest.edit_id, request: FactoryGirl.attributes_for(:request, name: "Larry Johnson")
        @testrequest.reload
        @testrequest.name.should eq("Larry Johnson")
    end
end