在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>
但是,如果我在每个块中定义变量,则没有错误。例如:
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
为什么在“之前:每个do”块中声明的变量在块中被识别?
答案 0 :(得分:4)
因为您将它们声明为each
块的本地变量,它立即超出范围。您需要将它们声明为实例变量,以使其可用于其他方法:
before :each do
@page_published = Page.create(attributes_for(:page))
@page_unpublished = Page.create(attributes_for(:page_unpublished))
end
答案 1 :(得分:1)
let!
块的主要场所,使其成为:
describe "Publishing" do
let! :page_published { Page.create(attributes_for(:page)) }
let! :page_unpublished { Page.create(attributes_for(:page_unpublished)) }
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