【问题标题】:collection_select not populating in rspec test with Capybara using FactoryGirl使用 FactoryGirl 在 Capybara 的 rspec 测试中未填充 collection_select
【发布时间】:2012-08-26 15:42:13
【问题描述】:

我正在尝试使用 capybara 测试从 collection_select 元素中选择一个值,出于某种原因,在运行 rspec 时不存在填充 collection_select 的数据,但在运行 rails 应用程序时却存在。

例子:

html 定义

<%= form_for(@notification) do |f| %>

    <%= f.label :device, "Select a Device to notify:" %>
    <%= f.collection_select :device_id, Device.all, :id, :device_guid, prompt: true %>

<% end %>

rspec 定义

describe "NotificationPages" do

  subject { page }

  let(:device) { FactoryGirl.create(:device) }
  let(:notification) { FactoryGirl.create(:notification, device: device) }

  describe "new notification" do
    before { visit new_notification_path }

    let(:submit) { "Create Notification" }

    describe "with valid information" do
      before do
        select(device.device_guid, from: 'notification_device_id')
        fill_in "Message", with: "I am notifying you."
      end

      it "should create a notification" do
        expect { click_button submit }.to change(Notification, :count).by(1)
      end
    end
  end
end

运行测试时,我收到以下错误消息:

Capybara::ElementNotFound: cannot select option, no option with text 'device_guid' in select box 'notification_device_id'

在测试期间,collection_select 中的 Device.all 调用似乎没有返回任何内容。关于我做错了什么有什么想法吗?

谢谢, 佩里

【问题讨论】:

    标签: ruby-on-rails rspec capybara factory-bot rspec-rails


    【解决方案1】:

    强制对 let 进行早期评估的更好方法是使用 !,如下所示:

    let!(:device) { FactoryGirl.create(:device) }
    

    这样你就不需要额外的代码行了。

    【讨论】:

      【解决方案2】:

      在您访问 new_notification_path 时,数据库中没有设备。发生这种情况是因为 let 是惰性求值的,所以它定义的方法在您第一次调用它时被调用,在您的测试中,只有在您执行 select(device.device_guid ...) 语句时才会发生这种情况。

      要确保在访问路径之前创建设备,您可以在 before 块中调用“设备”。

      before do
        device
        visit new_notification_path
      end
      

      【讨论】:

      • 就是这样。非常感谢您的解释。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      相关资源
      最近更新 更多