2
我在使用RSpec中的共享示例定义的变量时遇到了问题。这是我的测试: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上不可为例组
我需要做什么改变,使show_params
访问?我试过用it_behaves_like
而不是include_examples
,但没有运气。我也尝试删除context "navigation"
块无济于事。我需要跨多个控制器和动作执行此检查,因此似乎共享示例可能是重用代码的正确方法。
这工作很好!非常感谢你!我将共享示例放在一个单独的文件中('spec/controllers/shared_examples/authorized_action.rb'),在我的'spec/rails_helper.rb'中需要该目录,然后按照您的建议使用它! – Alexander