如何使用Rails与Capybara对React组件进行集成测试?
用React替代Rails ERB表单实现帖子创建功能
我最近基于Rails搭建了一个简易的帖子创建脚手架,但没采用标准的ERB表单,而是借助react-rails和browserify-rails这两个gem,手写了一个React组件来处理表单逻辑。
下面是我写的NewPostForm组件代码:
class NewPostForm extends React.Component { constructor(props) { super(props); this.state = {}; } render() { return( <form action="/posts" accept-charset="UTF-8" method="post"> {/* Rails表单必备的UTF-8标识隐藏域 */} <input name="utf8" type="hidden" value="✓" /> {/* 必须加入CSRF令牌,避免跨站请求伪造攻击 */} <input type="hidden" name="authenticity_token" value={this.props.authenticityToken} /> <div className="form-group"> <label htmlFor="post_title">帖子标题</label> <input type="text" name="post[title]" id="post_title" onChange={(e) => this.setState({ title: e.target.value })} value={this.state.title || ''} className="form-control" /> </div> <div className="form-group"> <label htmlFor="post_content">帖子内容</label> <textarea name="post[content]" id="post_content" rows="5" onChange={(e) => this.setState({ content: e.target.value })} value={this.state.content || ''} className="form-control" /> </div> <button type="submit" className="btn btn-primary">发布帖子</button> </form> ); } }
几个关键注意点:
- CSRF令牌传递:在Rails的ERB视图中渲染组件时,必须传递
authenticity_token参数,示例代码:<%= react_component 'NewPostForm', authenticityToken: form_authenticity_token %> - 参数命名规范:表单输入框的
name属性遵循Rails的嵌套参数格式(post[title]),这样后端控制器可以直接用强参数接收:# posts_controller.rb def create @post = Post.new(post_params) if @post.save redirect_to @post, notice: '帖子创建成功!' else # 这里可以结合React处理错误提示,或者返回原页面 render :new end end private def post_params params.require(:post).permit(:title, :content) end - 依赖配置:确保你的项目中已经安装了
react、react-dom依赖,并且browserify-rails已经正确配置,让Rails能打包React组件。
内容的提问来源于stack exchange,提问作者Pioz
相关产品推荐
相关产品推荐

