我正在尝试为嵌套的autolinks_controller编写Rspec测试。但是,我的创建操作后的重定向被破坏。成功创建自动链接后,我想重定向到特定网站内的自动链接(因此,website_autolink_path)。我的控制器规范看起来像这样:
describe "POST create when params[:website_id] are present" do
before(:each) do
@website = create(:website)
@autolink = attributes_for(:website_autolink, website_id: @website.id)
end
context "with valid attributes and params[:website_id] are present" do
it "saved the autolink in the database" do
expect{
post :create, website_id: @website, autolink: attributes_for(:website_autolink)
}.to change(Autolink, :count).by(1)
end
it "redirects to the 'index' page" do
post :create, website_autolink: @autolink, website_id: @website
response.should redirect_to website_autolink_path
end
end
end
此行不起作用:
response.should redirect_to website_autolink_path
给我错误信息:
ActionController::RoutingError:
No route matches {:action=>"show", :controller=>"autolinks"}
我的工厂看起来像这样:
自动链接:
FactoryGirl.define do
factory :website_autolink do
name "MyName"
url "http://www.myurl.nl"
association :website
end
end
网站:
FactoryGirl.define do
factory :website do
name "Test"
domain "http://www.test.nl"
end
end
我的AutolinkController:
def create
if params[:website_id].present?
@website = Website.find(params[:website_id])
@autolink = @website.autolinks.create(params[:autolink])
else
@autolink = Autolink.new(params[:autolink])
end
respond_to do |format|
if @autolink.save
if params[:website_id].present?
format.html { redirect_to [@website, @autolink], notice: "Autolink is met succes aangemaakt." }
else
format.html { redirect_to autolinks_path, notice: "Autolink is met succes aangemaakt." }
end
format.json { head :no_content }
else
format.html { render action: "new" }
format.json { render json: @autolink.errors, status: :unprocessable_entity }
end
end
end
在我的控制器中,以下行是我想要使用Rspec模拟的行:
format.html { redirect_to [@website, @autolink], notice: "Autolink is met succes aangemaakt." }
在我的本地主机中,它一切正常,但是为这个嵌套路线编写实际测试会让我感到麻烦。
答案 0 :(得分:1)
我刚刚找到了解决问题的方法。我现在的创建操作的控制器规范如下所示:
describe "POST create when params[:website_id] are present" do
context "with valid attributes and params[:website_id] are present" do
before(:each) do
@website = create(:website)
@autolink = attributes_for(:website_autolink, website: @website)
end
it "saved the autolink in the database" do
expect{
post :create, autolink: @autolink, website_id: @website.id
}.to change(Autolink, :count).by(1)
end
it "redirects to the 'index' page" do
post :create, autolink: @autolink, website_id: @website.id
response.should redirect_to website_autolink_path(@website, assigns(:autolink))
end
end
end
我只需要分配我的自动链接以重定向到嵌套路径。没有它,我的autolink的id就找不到了。