【问题标题】:RSpec System spec can see factory data from model but not from viewRSpec 系统规范可以从模型中看到工厂数据,但不能从视图中看到
【发布时间】:2026-02-22 02:00:01
【问题描述】:

我有一个系统规范,我调用了 3 个工厂: 公司has_many Shops has_many Shelves

在下面的代码中,我在规范和 ApplicationController 中都放置了一个调试器。从规范调用时,所有工厂都按预期创建。然后当我访问 root_url 时,我找不到相同的记录(或任何记录): - Company.count 返回 0 - Shop(find_by: id) 返回 nil(使用工厂创建的商店的 id)

当我将相同的工厂提供给 seed.rb 并在我的开发环境中将其拉起时,它会正确呈现页面和数据。

什么可能导致控制器忽略此规范中的数据?

规格:

RSpec.describe "changing the current shop", type: :system do
  let(:company) { create(:company, name: "Test co") }
  let(:first_shop) { create(:shop_with_shelves, name: "seeded shop", company: company) }
  let(:last_shelf) { create(:standby_shelf, name: "Cool Shelf", shop: first_shop) }

it "displays the name of the current shop" do
  first_shop
  last_shelf
  # debugger here identifies all models created as expected
  visit root_path
end

helper_method:

class ApplicationController < ActionController::Base
  helper_method :current_shop

  def current_shop
    # debugger here is unable to find any models Company.count = 0
    @current_shop ||= Company.first.current_shop
  end
end

在视图中是:

<%= current_shop.name %>

失败/错误:@current_shop ||= Company.first.current_shop

 NoMethodError:
   undefined method `current_shop' for nil:NilClass

如果进一步测试我能够看到系统规格会引发此错误,但功能规格不符合以下要求:

RSpec.describe "trying a system spec (this fails)", type: :system do
  let!(:company) { create(:company) }
  let!(:shop) { create(:shop, company: company, is_current: true) }
  it "gets to the shops page" do
    visit shops_path  
  end
end

RSpec.feature "trying a feature spec (this passes)", type: :feature do
  let!(:company) { create(:company) }
  let!(:shop) { create(:shop, company: company, is_current: true) }
  scenario "gets to the shops page" do
    visit shops_path  
  end
end

【问题讨论】:

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


    【解决方案1】:

    您的应用和测试都有自己的数据库连接。假设您使用的是现代版本的 Rails (5.1+),您需要启用事务测试并在应用程序和测试之间共享数据库连接。

    【讨论】:

    • 非常感谢!起初,您建议设置 config.use_transactional_fixtures: true 并从 Rails 助手中删除 DatabaseCleaner 并没有清除此错误。事实证明,我的规范设置数据也没有正确设置 current_shop,这导致了相同的错误消息。
    最近更新 更多