FactoryGirl build_stubbed & RSpec - 生成 ID 但在测试 Show 操作时找不到 ID
FactoryGirl build_stubbed & RSpec - Generates ID but fails to find id when testing Show action
这是我的测试。我收到的错误是 ActiveRecord::RecordNotFound:找不到 'id'=1001 的 MedicalStudentProfile。我使用 build_stubbed 正确吗?
RSpec 测试
RSpec.describe MedicalStudentProfilesController, type: :controller do
let!(:profile){build_stubbed(:medical_student_profile)}
let!(:user){build_stubbed(:user)}
describe 'GET show' do
it 'should show the requested object' do
sign_in user
get :show, id: profile.id
expect(assigns(:profile)).to eq profile
end
end
end
控制器
def show
@profile = MedicalStudentProfile.find params[:id]
end
build_stubbed 不会将记录保存到数据库,它只是为模型分配一个伪造的 ActiveRecord id 并存根数据库交互方法(如 save ),以便测试在它们是时引发异常叫。尝试使用:
let!(:profile){create(:medical_student_profile)}
build_stubbed
不会将记录保存到数据库中 - 它只是将模型存根以使其表现得像已被持久化一样。这对于模型规范或您实际不与数据库交互的其他场景非常有用。
但是对于请求和控制器规范,您需要使用 create
以便您的控制器可以从数据库加载记录。
let!(:profile){ create(:medical_student_profile) }
let!(:user){ create(:user) }
这是我的测试。我收到的错误是 ActiveRecord::RecordNotFound:找不到 'id'=1001 的 MedicalStudentProfile。我使用 build_stubbed 正确吗?
RSpec 测试
RSpec.describe MedicalStudentProfilesController, type: :controller do
let!(:profile){build_stubbed(:medical_student_profile)}
let!(:user){build_stubbed(:user)}
describe 'GET show' do
it 'should show the requested object' do
sign_in user
get :show, id: profile.id
expect(assigns(:profile)).to eq profile
end
end
end
控制器
def show
@profile = MedicalStudentProfile.find params[:id]
end
build_stubbed 不会将记录保存到数据库,它只是为模型分配一个伪造的 ActiveRecord id 并存根数据库交互方法(如 save ),以便测试在它们是时引发异常叫。尝试使用:
let!(:profile){create(:medical_student_profile)}
build_stubbed
不会将记录保存到数据库中 - 它只是将模型存根以使其表现得像已被持久化一样。这对于模型规范或您实际不与数据库交互的其他场景非常有用。
但是对于请求和控制器规范,您需要使用 create
以便您的控制器可以从数据库加载记录。
let!(:profile){ create(:medical_student_profile) }
let!(:user){ create(:user) }