Rspec删除名为testRecord的方法的activerecord列

时间:2019-06-20 17:02:56

标签: ruby-on-rails rspec

在我的应用程序中。如果package com.example.camerakitqr; public class Scanner extends AppCompatActivity { private CameraKitView cameraKitView; private Button detectButton; //GraphicOverlay graphicOverlay; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); cameraKitView = findViewById(R.id.camera); detectButton = findViewById(R.id.detectButton); detectButton.setOnClickListener(detectOnClickListener); } @Override protected void onStart() { super.onStart(); cameraKitView.onStart(); } @Override protected void onResume() { super.onResume(); cameraKitView.onResume(); } @Override protected void onPause() { cameraKitView.onPause(); super.onPause(); } @Override protected void onStop() { cameraKitView.onStop(); super.onStop(); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); cameraKitView.onRequestPermissionsResult(requestCode, permissions, grantResults); } private View.OnClickListener detectOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { cameraKitView.captureImage(new CameraKitView.ImageCallback() { @Override public void onImage(CameraKitView cameraKitView, byte[] photo ) { File savedPhoto = new File(Environment.getExternalStorageDirectory(), "photo.jpg"); try{ FileOutputStream outputStream = new FileOutputStream(savedPhoto.getPath()); outputStream.write(photo); outputStream.close(); Toast.makeText(getApplicationContext(), "File saved", Toast.LENGTH_SHORT).show(); } catch (java.io.IOException e){ e.printStackTrace(); Log.e("DEMO", "Not saved"); } } }); } }; 表具有users列,这导致activerecord向foo类添加foo命名实例方法,则User调用将返回MyEngine.bar
如果未定义该列,则'xyz'调用将返回MyEngine.bar。此行为更改是由'abc'方法调用中的以下代码引起的:bar

我该如何测试这种行为?

我想到的测试流程如下:

current_user.respond_to?(:foo)

我希望能够临时删除it "does something" do user = FactoryBot.create(:user, foo: "something") sign_in(user) expect(MyEngine.bar).to eq "xyz" # remove foo here to test how user responds when it's missing expect(MyEngine.bar).to eq "abc" end 列以进行测试。

1 个答案:

答案 0 :(得分:0)

根据我们在评论部分的讨论,假设您可以对current_user进行存根/控制,我将要做的是:

it "does something" do
  user = FactoryBot.create(:user, foo: "something")
  sign_in(user)
  expect(MyEngine.bar).to eq "xyz"

  # here we remove foo method for only this instance of user
  user.singleton_class.class_eval {undef :foo}
  # Now stub call to current_user, of-course this line 
  # will adapt your code in MyEngine and how it calls current_user
  # also note expect, you may use allow here instead, but i would prefer expect
  expect(MyEngine).to receive(:current_user).and_return(user)
  expect(MyEngine.bar).to eq "abc"
  # You will get back foo method on any new user instances:
  # user = User.find(user.id)
end

这种方法极大地限制了后果。根据我的理解应该解决您的问题。