【发布时间】:2018-04-17 08:43:46
【问题描述】:
我已经创建了一个小脚手架,用于使用 Rails 创建帖子,但使用 erb 的标准表单我创建了一个简单的 React 组件(我使用 gem react-rails 和 browserify-rails)。
您可以找到包含所有源代码的示例 repo here!
React 组件如下所示:
class NewPostForm extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
render() {
return(
<form action="/posts" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="✓"/>
<input type="hidden" name="authenticity_token" value={this.props.authenticityToken}/>
<div className="field">
<label for="post_title">Title</label>
<input type="text" name="post[title]" id="post_title" onChange={(e) => this.setState({title: e.target.value})} />
</div>
<div className="field">
<label for="post_body">Body</label>
<textarea name="post[body]" id="post_body" onChange={(e) => this.setState({body: e.target.value})}></textarea>
</div>
{ this.state.title &&
<div class="actions">
<input type="submit" name="commit" value="Create Post" data-disable-with="Create Post"/>
</div>
}
</form>
)
}
}
请注意,只有在填充了标题输入字段时,才会将提交按钮添加到 DOM。
文件app/views/posts/_form.html.erb是这样的:
<%= react_component 'NewPostForm', {authenticityToken: form_authenticity_token.to_s}, {prerender: true} %>
现在我已经创建了这个使用 Capybara 的集成测试:
require 'test_helper'
class PostCreationTest < ActionDispatch::IntegrationTest
test "post creation" do
visit new_post_path
fill_in 'post[title]', with: 'Big News'
fill_in 'post[body]', with: 'Superman is dead!'
click_button 'Create Post' # <=== DO NOT FIND THIS BUTTON CAUSE IS ADDED WITH REACT
assert page.has_content?('Post was successfully created.')
end
end
测试失败并出现此错误:
Run options: --seed 21811
# Running:
E
Error:
PostCreationTest#test_post_creation:
Capybara::ElementNotFound: Unable to find visible button "Create Post"
test/integration/post_creation_test.rb:9:in `block in <class:PostCreationTest>'
bin/rails test test/integration/post_creation_test.rb:5
在 test_helper.rb 中,我已将 Capybara 配置为使用 poltergeist 驱动程序。
Capybara.register_driver :poltergeist do |app|
Capybara::Poltergeist::Driver.new(app, {
js_errors: false,
phantomjs_options: ['--ignore-ssl-errors=yes', '--ssl-protocol=any'],
debug: false,
timeout: 500,
phantomjs: File.absolute_path(Phantomjs.path)
})
end
Capybara.javascript_driver = :poltergeist
Capybara.server_port = 3001
如果我在反应组件中始终显示提交按钮(删除{ this.state.title &&),则测试成功通过。
那么,有没有办法让这个测试与这个设置和 React 组件一起工作?
【问题讨论】:
-
超人没有死。
标签: ruby-on-rails reactjs capybara integration-testing