Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamic object name in test helper #165

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,29 @@ end

For more complex components, we recommend the [`rspec-html-matchers` gem](https://github.com/kucaahbe/rspec-html-matchers).

### Minitest

#### Configuration

```rb
# test/test_helper.rb
ViewComponent::TestCase.include(ViewComponent::Form::TestHelpers)
```

#### Example

```rb
test "renders a text field" do
object = User.new # replace with a model of your choice
form = form_with(object)
options = {}

render_inline(described_class.new(form, object_name, :first_name, options))

assert_selector "input[type=text][name='user[first_name]'][id='user_first_name']"
end
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
Expand Down
10 changes: 6 additions & 4 deletions lib/view_component/form/test_helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ module ViewComponent
module Form
module TestHelpers
def form_with(object, builder: ViewComponent::Form::Builder, **options)
object_name = if object.class.respond_to?(:model_name)
object.class.model_name.param_key
else
:user
end

builder.new(object_name, object, template, options)
end

def object_name
:user
end

if Gem::Version.new(Rails::VERSION::STRING) >= Gem::Version.new("6.1")
def template
lookup_context = ActionView::LookupContext.new(ActionController::Base.view_paths)
Expand Down
Loading