Home > Mobile >  how to pass value from spec file to controller
how to pass value from spec file to controller

Time:09-16

I want to write rspec test to existing code. Existing code is

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

I want to assign value @@userID from rspec file. How to assign value to it in person_spec file

CodePudding user response:

you could use class_variable_set like an actionmailer test setup here(although this is MiniTest setup but the idea is same, you could use for rspec as well).

so your test case look like this

# 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

or if you don't care side effect:

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

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