【问题标题】:how to pass value from spec file to controller如何将值从规范文件传递到控制器
【发布时间】:2021-09-13 11:08:16
【问题描述】:

我想为现有代码编写 rspec 测试。现有代码是

def getperson
  log_middle('getperson') do
    @filteredPersons = Person.where(['UserID=?', @@userID])
  end
  @filteredPersons
end

我想从 rspec 文件中分配值 @@userID。如何在 person_spec 文件中为其赋值

【问题讨论】:

  • 如何在“生产”代码中为其赋值?
  • 我只想为那个方法写单元测试
  • 您不是在测试该方法,而是通过调用该方法来测试类行为。所以你需要“知道”@@userId 在类中是如何设置的。

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


【解决方案1】:

你可以像an actionmailer test setup here一样使用class_variable_set(虽然这是MiniTest的设置但是思路是一样的,你也可以使用rspec)。

所以你的测试用例看起来像这样

# test_helper
def with_user_id(user_id)
  old_user_id = ClassUnderTest.class_variable_get(:@@userID)
  ClassUnderTest.class_variable_set(:@@userID, user_id)
  yield
ensure
  ClassUnderTest.class_variable_set(:@@userID, old_user_id)
end

# your test
with_user_id(123) do
  get_person ...
  expect(...)
end

或者如果你不关心副作用:

# ...
context "@@userID is 123" do
  before(:each) do
    ClassUnderTest.class_variable_set(:@@userID, 123)
  end

  it "should ..." do
    getperson ...
    expect(...).to ...
  end
end
# ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    相关资源
    最近更新 更多