我有一个简单的 rspec Controller 测试,用于基本的 CRUD 功能。我最近将Friendly_id 添加到我的 Controller 中 - 现在所有测试都失败了。
describe "PATCH update" do
context "where the record is found" do
before do
allow(model).to receive(:find).and_return(instance)
end
context "where the record is a root" do
before do
allow(instance).to receive(:root?).and_return(true)
end
context "where the record is updated" do
before do
allow(instance).to receive(:save).and_return(true)
patch :update, instance.slug
end
it "should set a flash notice" do
flash[:notice].should_not be_nil
end
it "should redirect to panel page" do
response.should redirect_to(admin_corporate_pages_path)
end
end
end
end
end
所有这些都失败并出现以下错误,
1) Admin::CorporatePagesController for authenticated users GET edit returns http success
Failure/Error: get :edit, id: corporate_page
NoMethodError:
undefined method `friendly' for #<Class:0x007f993a956b88>
2) Admin::CorporatePagesController for authenticated users PATCH update where the record is found where the record is a root where the record is updated should set a flash notice
Failure/Error: patch :update, instance.slug
ActionController::UrlGenerationError:
No route matches {:action=>"update", :controller=>"admin/corporate_pages"}
这是相关的 Controller ,
def update
if @corp_page
@path = (@corp_page.root? ? admin_corporate_pages_path : admin_corporate_page_path(@corp_page.root))
if @corp_page.update_attributes(params[:corporate_page])
flash[:notice] = 'Page updated'
redirect_to @path and return
else
flash[:error]= 'There was an error'
render :new and return
end
else
flash[:error] = "Record not found"
end
redirect_to admin_corporate_pages_path
end
private
def get_corp_page
@corp_page = CorporatePage.friendly.find(params[:id])
end
我不明白它如何产生影响,因为友好的 id 无论如何都使用 :id 函数。它怎么会对测试产生如此大的影响?
最佳答案
有两件事您需要解决。首先,您的实例没有设置 slug 属性,这会导致错误 2。另外您的调用似乎不正确,应该是:
patch :update, id: instance.to_param # Let model decide which column it is to use
第二个错误是由以下原因引起的:
allow(model).to receive(:find).and_return(instance)
将其更改为:
allow(model).to receive_message_chain(:friendly, :find).and_return(instance)
关于ruby-on-rails - Friendly_id 和 rspec Controller 测试,找到正确的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26259189/