gpt4 book ai didi

ruby-on-rails - "before :each do" block 未在 rspec 中运行

转载 作者:行者123 更新时间:2023-12-02 05:01:55 25 4
gpt4 key购买 nike

在 rspec 测试中,我尝试在测试运行之前初始化两个变量,如下所示

  describe "Publishing" do
before :each do
page_published = Page.create(attributes_for(:page))
page_unpublished = Page.create(attributes_for(:page_unpublished))
end
it "returns published pages" do
expect(Page.published).to eq [page_published]
end
it "returns unpublished pages" do
expect(Page.unpublished).to eq [page_unpublished]
end
end

当我这样做时,出现错误:

1) Page Publishing returns unpublished pages
Failure/Error: expect(Page.unpublished).to eq [page_unpublished]
NameError:
undefined local variable or method `page_unpublished' for #<RSpec::Core::ExampleGroup::Nested_1::Nested_4:0x0000010355b8c0>

但是,如果我在每个 it block 中定义变量,就没有错误。例如:

  describe "Publishing" do
it "returns published pages" do
page_published = Page.create(attributes_for(:page))
expect(Page.published).to eq [page_published]
end
it "returns unpublished pages" do
page_unpublished = Page.create(attributes_for(:page_unpublished))
expect(Page.unpublished).to eq [page_unpublished]
end
end

为什么在“before :each do” block 中声明的变量在 it block 中不被识别?

最佳答案

因为您将它们声明为 each block 的局部变量,这会立即超出范围。您需要将它们声明为实例变量,以便其他方法可以使用它们:

before :each do
@page_published = Page.create(attributes_for(:page))
@page_unpublished = Page.create(attributes_for(:page_unpublished))
end

关于ruby-on-rails - "before :each do" block 未在 rspec 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16926728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com