我当时使用响应者gem为我的应用编写测试。 这是我的路线:
resources :sites do
resources :pages, shallow: true
end
我的PagesController代码块
def create
respond_with(@page = @site.pages.create(page_params))
end
def find_site
@site = current_user.sites.find(params[:site_id])
end
测试失败:
sign_in_user
let(:user_2) { create(:user) }
let(:site) { create(:site, user: @user) }
let(:page) { create(:page, site: site, user: @user) }
describe 'POST #create' do
context 'with valid attributes' do
it 'associates new page with the site' do
expect { post :create, params: { page: attributes_for(:page), site_id: site } }.to change(site.pages, :count).by(1)
end
it 'redirects to show view' do
post :create, params: { page: attributes_for(:page), site_id: site }
expect(response).to redirect_to page_path(assigns(:page))
end
end
错误如下:
1) PagesController POST #create with valid attributes associates new page with the site
Failure/Error: expect { post :create, params: { page: attributes_for(:page), site_id: site } }.to change(site.pages, :count).by(1)
expected #count to have changed by 1, but was changed by 0
# ./spec/controllers/pages_controller_spec.rb:37:in `block (4 levels) in <top (required)>'
2) PagesController POST #create with valid attributes redirects to show view
Failure/Error: expect(response).to redirect_to page_path(assigns(:page))
ActionController::UrlGenerationError:
No route matches {:action=>"show", :controller=>"pages", :id=>nil}, missing required keys: [:id]
# ./spec/controllers/pages_controller_spec.rb:42:in `block (4 levels) in <top (required)>'
如果我在第一次测试中将site.pages更改为Page-它实际上正在工作。
所以我真的很困惑如何修复此测试以及错误在哪里。
问题出在我的PagesController上,方法创建应该像这样
def create
@page = @site.pages.build(page_params)
@page.user = current_user
@page.save
respond_with(@page)
end
答案 0 :(得分:1)
问题出在我的PagesController上,方法创建应该像这样
def create
@page = @site.pages.build(page_params)
@page.user = current_user
@page.save
respond_with(@page)
end