【问题标题】:Rails Rspec testing html select optionsRails Rspec 测试 html 选择选项
【发布时间】:2012-10-19 03:27:00
【问题描述】:

我正在尝试使用 rspec 来测试从 select 标记中选择一个值。 select 标记应列出数据库中每个用户的所有名称。当我浏览该站点时,它可以工作。但测试似乎没有看到 FactoryGirl 创建的用户名:

错误是:

cannot select option, no option with text 'Person 4' in select box 'receiver_id'

这是 message_pages 规范的一部分:

let(:user) { FactoryGirl.create(:user) }
let(:other_user) { FactoryGirl.create(:user) }
before do
    select other_user.name, :from => 'message[receiver_id]'
    fill_in "Subject", with: "Hello"
    fill_in "Body", with: "It's time to have fun!"
end 

这是我的视图的 HTML 输出:

<label for="message_receiver_id">Receiver</label>
<select id="message_receiver_id" name="message[receiver_id]"><optionvalue="12">John</option>
<option value="13">Tom</option>
<option value="9">Jay</option>
<option value="14">Bob</option></select>

【问题讨论】:

  • 我用 select user.name 代替,它通过了。显然 other_user 没有被创建?我正在使用 FactoryGirl 音序器。
  • 你可以使用let!来避免懒惰评估

标签: ruby-on-rails testing rspec-rails


【解决方案1】:

这看起来像是一个惰性求值问题,在使用 let 时很常见。来自documentation

注意 let 是惰性求值的:直到它定义的方法第一次被调用时才会求值。你可以使用让!在每个示例之前强制调用方法。

所以userother_user 只会在你第一次调用它们时创建,如果你已经渲染了页面,那就太晚了。尝试将let 调用切换到let!,看看是否能解决问题。

(虽然你说切换到user.name 有效,但很有趣。你能发布规范中的其他初始化代码吗?)

【讨论】:

  • 我认为你是对的。实际上,在进行选择测试之前,我确实调用了用户,但我从未调用过 other_user。谢谢!现在我知道什么是惰性求值了
  • 这可以解释为什么user 有效但other_user 无效。很高兴答案有帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-13
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多