【发布时间】: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