【问题标题】:RSpec Cannot Use Defined Variables in Shared ExamplesRSpec 不能在共享示例中使用定义的变量
【发布时间】:2016-10-09 19:19:24
【问题描述】:

我在为 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" 块无济于事。我需要跨多个控制器和操作执行此检查,因此似乎共享示例可能是重用代码的正确方法。

【问题讨论】:

    标签: ruby-on-rails testing rspec


    【解决方案1】:

    这里的问题是记忆化的 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
    

    【讨论】:

    • 效果很好!非常感谢你!我将共享示例放在单独的文件 (spec/controllers/shared_examples/authorized_action.rb) 中,在我的 spec/rails_helper.rb 中需要该目录,然后按照您的建议使用它!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多