镜像站点 · 本页由第三方 GitHub 只读镜像提供,非 GitHub 官方站点,不接受任何登录或凭据输入。前往 github.com
Skip to content

Use of instance_variable_set in testing? #1

Closed

Description

@rlmoser99

Is using instance_variable_set a code smell, when used only in testing? For example:

Is it better to have @guess as a parameter, to be able to easily create a new instance of game for tests subject(:game) { described_class.new(0, 9, 4) }

def initialize(min, max, guess = nil)
  @min = min
  @max = max
  @guess = guess
end

Or is it better to have less arguments and to use game.instance_variable_set(:@guess, 4) in the few tests that require a value for @guess?

def initialize(min, max)
  @min = min
  @max = max
  @guess = nil
end

Activity

  1. KevinMulhern commented on Oct 30, 2020

    @KevinMulhern
    Member

    @rlmoser99 yeah I believe that its a code smell and your solution of passing the param in during initialisation is how it should be done. It fits nicely with the open closed principle. Having to use instance_variable_set seems like a work around.

  2. rlmoser99 commented on Oct 31, 2020

    @rlmoser99
    MemberAuthor

    Awesome! Thanks for your input! It is great to know with confidence that we should not be using instance_variable_set in testing.

  3. added a commit that references this issue on Sep 6, 2022
  4. added a commit that references this issue on May 13, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions