我有一个新操作,该操作将创建一个圆并将当前的父级分配为其管理员:
def new
return redirect_to(root_path) unless parent
@circle = Circle.new(administrator: parent)
end
我正在尝试测试是否正确设置了管理员ID,并且已经这样写出了我的测试:
context 'with a parent signed in' do
before do
sign_in parent
allow(controller).to receive(:circle).and_return(circle)
allow(Circle).to receive(:new).and_return(circle)
end
it 'builds a new circle with the current parent as administrator' do
get :new
expect(@circle.administrator).to equal(parent)
end
end
这显然会引发错误的@circle
IS nil
。如何访问尚未从控制器测试中保存的新对象?我猜这是允许/允许的某种变体,但正如我所说,到目前为止,我的所有搜索都没有产生任何结果。
您正在错误地解决问题。测试控制器的行为。不是它的实现。
如果这是旧版应用程序,则可以assigns
用来访问@circle
控制器的实例变量:
context 'with a parent signed in' do
before do
sign_in parent
end
it 'builds a new circle with the current parent as administrator' do
get :new
expect(assigns(:circle).administrator).to equal(parent)
end
end
但是Rails 5删除了assigns
,在新项目中不鼓励使用它。相反,我将使用功能规格并实际测试创建圆的步骤:
require 'rails_helper'
RSpec.feature 'Circles' do
let(:parent) { create(:parent) }
context "a guest user" do
scenario "can not create circles" do
visit new_circle_path
expect(page).to have_content 'Please sign in'
end
end
context "when signed in" do
background do
login_as parent
end
scenario "can create circles" do
visit new_circle_path
fill_in 'name', with: 'Test Circle'
expect do
click_button 'Create circle'
end.to change(parent.circles, :count).by(+1)
expect(page).to have_content 'Test Circle'
end
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句