RSpec集成测试fill_in报错:无法找到可用的post[date]字段
解决RSpec+Capybara测试中的Capybara::ElementNotFound错误
问题描述
使用RSpec进行集成测试时,调用fill_in "post[date]"触发错误:
Unable to find field "post[date]" that is not disabled
以下是相关代码:
测试代码
require 'rails_helper' describe 'navigate' do describe "index" do before do @user = User.create(email:"test@test.com", password:"test123", password_confirmation:"test123", first_name:"Umair", last_name:"Ahmed") end it "can be reached successfully" do visit posts_path expect(page.status_code).to eq(200) end end describe "new and create" do before do user = User.create(email:"test@test.com", password:"test123", password_confirmation:"test123", first_name:"Umair", last_name:"Ahmed") login_as(user, scope: user) # 此处存在错误 visit new_post_path end it "has a new form" do expect(page.status_code).to eq(200) end it "will fill in details of form" do fill_in "post[date]", with: Date.today fill_in "post[rationale]", with: "something rationale" click_on "Save" expect(page).to have_content("something rationale") end it "will have a user associated with it" do fill_in "post[date]", with: Date.today fill_in "post[rationale]", with: "User Association" click_on "Save" expect(User.first.posts.first.rationale).to eq("User Association") end end end
Post模型代码(post.rb)
class Post < ApplicationRecord belongs_to :user, optional: true validates_presence_of :date, :rationale end
视图代码(views/posts/new.html.erb)
<%= form_for @post do |f| %> <%= f.date_field :date %> <%= f.text_area :rationale %> <%= f.submit "Save" %> <% end %>
解决方案
1. 修正login_as的scope参数
login_as方法的scope参数需传入符号类型的模型名(如:user),而非用户实例。错误的scope会导致登录失败,页面被重定向到登录页,自然找不到表单字段。
修正后的before块代码:
before do user = User.create(email:"test@test.com", password:"test123", password_confirmation:"test123", first_name:"Umair", last_name:"Ahmed") login_as(user, scope: :user) # 修正为:user visit new_post_path end
2. 确认控制器初始化@post
确保PostsController的new方法中初始化了@post,否则form_for无法正确生成表单字段:
# app/controllers/posts_controller.rb class PostsController < ApplicationController before_action :authenticate_user!, only: [:new, :create] def new @post = Post.new # 必须初始化@post end # ...其他方法 end
3. 验证页面是否正确加载
如果问题仍存在,可在测试中添加puts page.html查看当前页面内容,确认是否成功跳转到新建文章页面,而非登录或其他页面。
验证修正后的测试
修正上述问题后,重新运行测试,fill_in方法应该能正常找到post[date]字段,完成表单填充及后续断言。
内容的提问来源于stack exchange,提问作者uma
相关产品推荐
相关产品推荐

