【问题标题】:How to pass a variable in callbacks during rspec testing?如何在 rspec 测试期间在回调中传递变量?
【发布时间】:2021-03-31 06:37:27
【问题描述】:

我有回调名称 authentication_admin_user 。如果当前用户的电子邮件 ID 是“adminuser@admin.com”,它将返回 true

def authenticate_admin_user!
 if Current.user.blank? || Current.user.email != "adminuser@admin.com"
  redirect_to courses_path, danger: "Admin login required" 
 end 
end

这个回调在我调用 new action 时运行。 在测试新操作时,我必须设置 Current.user 值

describe "GET /new" do
    describe "Create course with admin login"
      it "will not renders a new course page" do
        get new_course_url
        expect(response).to_not be_successful
      end
      it "will render a new course page" do
        get new_course_url
        expect(response).to be_successful
      end
  end

如何设置 Current.user 的值? PS:这里的 Current 是一个 ActiveSupport::Currentattributes 模型,而 user 是 Current 类中的一个属性。

【问题讨论】:

  • 你能模拟一下吗?
  • 怎么做?我不明白
  • 以萨钦的回答为例。

标签: ruby-on-rails testing rspec controller rspec-rails


【解决方案1】:

尝试存根用户对象:

let(:user) { double(:user, email: 'adminuser@admin.com') }

before do
  allow(Current).to receive(:user).and_return(user)
end

或者只是

before do
  allow(Current).to receive(:user).and_return(nil)
end

【讨论】:

  • 很好,instance_double(User) 是首选(如果您尝试使用 User 对象上不存在的方法存根它会失败。
猜你喜欢
  • 2017-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多