gpt4 book ai didi

ruby-on-rails - RSpec 不能在共享示例中使用定义的变量

转载 作者:行者123 更新时间:2023-11-28 20:05:47 25 4
gpt4 key购买 nike

我在为 RSpec 中的共享示例使用定义变量时遇到问题。这是我的测试:

RSpec.shared_examples "check user logged in" do |method, action, params|
it "redirects to the sign in page if the user is not logged in" do
send(method, action, params)
expect(response).to redirect_to(signin_url)
end
end

RSpec.describe UsersController, type: :controller do
describe "GET #show" do
let(:user) { FactoryGirl.create(:user) }
let!(:show_params) do
return { id: user.id }
end

context "navigation" do
include_examples "check user logged in", :get, :show, show_params
end
end
end

在测试中,我正在检查以确保用户需要先登录才能执行操作。我收到以下错误消息:

method_missing': show_params is not available on an example group

我需要更改什么才能使 show_params 可访问?我试过使用 it_behaves_like 而不是 include_examples 但没有成功。我也试过删除 context "navigation" block 无济于事。我需要跨多个 Controller 和操作执行此检查,因此共享示例似乎是重用代码的正确方法。

最佳答案

这里的问题是记忆化的 let 助手 show_params 是在示例之外调用的。

您可以简单地从包含示例的外部作用域引用 let,而不是传递参数:

RSpec.describe UsersController, type: :controller do
let(:user) { FactoryGirl.create(:user) }
describe "GET #show" do
let(:action) { get :show, id: user }
it_should_behave_like "an authorized action"
end
end

RSpec.shared_examples "an authorized action" do
it "denies access" do
action
expect(response).to redirect_to(signin_url)
end
end

这是一个非常强大的模式,自 last let always wins 以来,您可以使用约定优于配置的方法。 .

RSpec.describe UsersController, type: :controller do
let(:user) { FactoryGirl.create(:user) }
describe "GET #show" do
let(:action) { get :show, id: user }
it_should_behave_like "an authorized action"

context "when signed in" do
before { sign_in user }
let(:action) { get :show, id: other_user }
context 'when viewing another user' do
it_should_behave_like "an authorized action"
end
end
end
end

关于ruby-on-rails - RSpec 不能在共享示例中使用定义的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39947567/

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