如何将 Rails Rspec 测试中的随机变量发送到应用程序控制器? (设计、工厂机器人、水豚)

问题描述 投票:0回答:1

我需要一种方法来根据访问启动页面的人的 IP/位置来指定各种重定向到特定页面的方法。

scenario "User from asdf sees ASDF page" do

    create_user_from_asdf

    visit root_path
    
    expect(page).to have_css("#egativenay_onyay_erqway_ehyay")

  end

从asdf创建factorybot用户是多余的,因为在登录(设计)之前没有用户,否则我可以创建一个具有某些随机属性的用户来触发应用程序控制器等中的代码。

通常,使用 request.host 或 request.location.country 过滤到各个启动页面的重定向

在进行Rspec测试时,访问root_path时,request.host为水豚标准的“www.example.com”,request.location.country为“Reserved”。

我该如何编辑这个?

或者我如何从 Rspec 示例/场景测试中以某种方式通知应用程序控制器要启动某些代码来修改 ASDF 页面的路径?

...我如何从 Rspec 发送可从应用程序控制器访问的随机变量?

ruby-on-rails rspec devise capybara factory-bot
1个回答
0
投票

您可以模拟您关心的请求对象方法...

这会嘲笑

request.host

scenario "User from 'host' sees HOST page" do
  allow_any_instance_of(ActionDispatch::Request).to receive(:host).and_return("host")

  visit root_path    

  expect(page).to have_css("#host")
end

而且,这会嘲笑

request.location.country

scenario "User from country sees COUNTRY page" do
  location = instance_double("location"), country: "country")
  allow_any_instance_of(ActionDispatch::Request).to receive(:location).and_return(location)

  visit root_path    

  expect(page).to have_css("#country")
end

注意:为了抢占关于

allow_any_instance_of
是反模式的不可避免的评论,在这种情况下有必要获取由 Rails 启动的 Request 类实例的句柄。

注 2:还可以通过使用 Rack::Test 来解决此问题,它使您可以访问设置请求标头。

© www.soinside.com 2019 - 2024. All rights reserved.